python库--pandas--Series.str--字符串处理

原数据

import pandas as pd
a = pd.Series(['aSd', 'asd', 'dfd fsAsf sfs'])
b = pd.Series([None, 'asd', 'fgh'])
index a b
0 aSd None
1 asd asd
2 dfd fsAsf sfs fgh

字符大小写转换

a.str.lower()
a.str.upper()
a.str.title()
a.str.capitalize()
a.str.swapcase()
lower upper title capitalize swapcase
0 asd ASD Asd Asd AsD
1 asd ASD Asd Asd ASD
2 dfd fsasf sfs DFD FSASF SFS Dfd Fsasf Sfs Dfd fsasf sfs DFD FSaSF SFS

字符串拼接

自身拼接

a.str.cat(sep=',')

aSd,asd,dfd fsAsf sfs

与其它series拼接

a.str.cat(a)
a.str.cat(['aSd', 'asd', 'dfd fsAsf sfs'])
a + a
index value
0 aSdaSd
1 asdasd
2 dfd fsAsf sfsdfd fsAsf sfs
a.str.cat(a, sep=',')
a.str.cat(['aSd', 'asd', 'dfd fsAsf sfs'], sep=',')
a + ',' + a
index value
0 aSd,aSd
1 asd,asd
2 dfd fsAsf sfs,dfd fsAsf sfs

数据含有None/NaN的情况

b.str.cat(sep=',')

asd,fgh

# 将NaN替换为指定字符串进行操作
a.str.cat(sep=',', na_rep='???')

???,asd,fgh

  • 剩下的情况除将NaN替换为指定字符之外跟上述示例一样, 这里不再进行演示

字符填充/插入/扩展

# 向两端填充指定字符到指定长度
a.str.center(width=10, fillchar='?')
a.str.pad(width=10, side='both', fillchar='?')
# 在右侧填充指定字符到指定长度
a.str.ljust(width=10, fillchar='?')
a.str.pad(width=10, side='right', fillchar='?')
# 在右侧填充指定字符到指定长度
a.str.rjust(width=10, fillchar='?')
a.str.pad(width=10, side='left', fillchar='?')
center ljust rjust
0 ???aSd???? aSd??????? ???????aSd
1 ???asd???? asd??????? ???????asd
2 dfd fsAsf sfs dfd fsAsf sfs dfd fsAsf sfs
# 每隔指定个字符插入一个换行符
a.str.wrap(width=2)
# 在字符串前面填充0到指定长度
a.str.zfill(width=10)
# 将字符串扩展n倍
a.str.repeat(repeats=2)
# 为每一个元素指定扩展倍数
a.str.repeat(repeats=[2, 2, 2])
wrap zfill repeat
0 aS d 0000000aSd aSdaSd
1 as d 0000000asd asdasd
2 df d fs As f sf s dfd fsAsf sfs dfd fsAsf sfsdfd fsAsf sfs
  • join() 在字符间插入字符
a.str.join(sep='?')
# 等同于
a.map(lambda x: '?'.join(x))
  • 因此也出现了一种特殊情况, 元素不是字符串但可以使用join方法
  • 经过不完全证明, '?'.join() 中支持的参数作为Series的元素是都可使用此方法
pd.Series([['1', '2', '3']]).join('?')

字符串内容判断

以下方法返回由True和False组成的Series

  • contains(): 判断指定字符串或正则表达式是否在序列或索引中
参数 说明
pat 字符串或正则表达式
case=True 是否区分大小写
flags=0 可传入re.IGNORECASE之类的参数
na=nan 缺失值填充
regex=True 是否使用正则表达式匹配
  • endswith(): 判断是否以给定的字符串结尾
参数 说明
pat 字符串
na=nan 缺失值填充
  • match(): 判断是否以给定的字符串开头(支持正则)
参数 说明
pat 字符串或正则表达式
case=True 是否区分大小写
flags=0 可传入re.IGNORECASE之类的参数
na=nan 缺失值填充
as_indexer=None 弃用
方法 说明
.isalnum() 字符串至少包含一个字符且所有字符都是字母(汉字)或数字则返回True
.isalpha() 字符串至少包含一个字符且所有字符都是字母(汉字)则返回True
.isdigit() 只包含数字(可以是: Unicode, 全角字符, bytes(b'1'), 罗马数字)
.isspace() 只包含空白符
.islower() 至少包含一个小写字符, 且不包含大写字符
.isupper() 至少包含一个大写字符, 且不包含小写字符
.istitle() 所有单词大写开头其余小写(标题化)
.isnumeric() 只包含数字字符
.isdecimal() 只包含数字(Unicode字符, 全角字符)

查找

  • extract(): 使用正则表达式提取需要的内容(只返回第一次匹配到的内容)
  • extractall(): 使用正则表达式提取需要的内容(返回所有匹配到的内容
参数 说明
pat 正则表达式(必须含有捕获组, 超过一个必然返回DataFrame)
若捕获组设有name则将作为返回的列标签
flags=0 可传入re.IGNORECASE之类的参数
expand=None True: 返回DataFrame(未来版本默认值)
False: 返回S/I/DataFrame(现在版本默认值)
extractall() 方法无此参数
a.str.extract('([A-Z]+)')
a.str.extract('([A-Z]+)(s*)')
([A-Z]+) - ([A-Z]+)(s*)
0 S - S
1 NaN - NaN  NaN
2 A - A    s
a.str.extractall('(?P<field1>[sSdf]+)(?P<field2>[ds])')
field1 field2 说明
match
0 0 S d 第1行第1个匹配结果
1 0 s d 第2行第1个匹配结果
2 0 df d 第3行第1个匹配结果
1 f s 第3行第2个匹配结果
2 sf s 第3行第3个匹配结果
  • 检索sub在字符串中的位置, 可以指的那个开始检索和结束检索的位置
    1. find(): 检索不到返回-1
    2. rfind(): 从右往左检索, 检索不到返回-1
    3. index(): 检索不到触发异常
    4. rindex(): 从右往左检索, 检索不到返回-1
a.str.find(sub='s')
# 从第6个字符开始查找到第10个字符结束查找
a.str.find(sub='s', start=6, end=10)
(sub='s') (sub='s', start=6, end=10)
0 -1 -1
1 1 -1
2 5 7
  • findall(): 以列表形式返回正则表达式所有匹配结果
a.str.findall(pat='[sSdf]+')
a.map(lambda x: re.findall('[sSdf]+', x))
结果
0 [Sd]
1 [sd]
2 [dfd, fs, sf, sfs]
  • get(): 获取指定位置的字符
a.str.get(i=1)
结果
0 S
1 s
2 f

统计

  • count() 统计指定字符串(支持正则)在序列字符串中出现的次数
  • len() 返回序列字符串的长度
a.str.count(pat='s', flags=0)
a.str.len()
count len
0 0 3
1 1 3
2 4 13

转码

  • encode(): 编码str --> bytes
  • decode(): 解码bytes --> str
参数 说明
encoding 编码方式
error='static' static: 编码/解码失败抛出异常
ignore: 编码/解码失败自动忽略非法字符
replace: 编码/解码失败则使用 ? 替代非法字符
xmlcharrefreplace: 则引用XML的字符.
c = pd.Series(['中文', 'ud83easd'])
c.str.encode('utf8', 'ignore')
c.str.encode('utf8', 'replace')
c.str.encode('utf8', 'xmlcharrefreplace')
ignore replace xmlcharrefreplace backslashreplace
1 b'asd' b'?asd' b'&#55358;asd' b'ud83easd'
# 中国: b'xe4xb8xadxe6x96x87'
d = pd.Series([b'xe4xb8xadxe6x96'])
d.str.decode('utf8', 'ignore')
ignore replace xmlcharrefreplace backslashreplace
1 中� NaN 中xe6x96
  • normalize(): 返回字符串的Unicode标准格式

删减/截取

  • strip(to_strip=None): 删除两侧指定字符, 默认删除空白符
  • lstrip(to_strip=None): 删除左侧指定字符, 默认删除空白符
  • rstrip(to_strip=None): 删除右侧指定字符, 默认删除空白符
  • slice() 截取子字符串
参数 说明
start=None 开始位置
stop=None 结束位置
step=None 步长

分割/替换

  • split() 使用指定字符分割字符串, 支持正则
  • rsplit() 从右侧开始分割
参数 说明
pat=None 分隔符, 默认空白符
n=-1 分割次数, 默认全部
expand=False True: 返回DataFrame/MultiINdex
False: 返回Series/Index
  • get_dummies(): 对字符串分割, 并返回每个分割结果出现的次数
>>> pd.Series(['a|b', 'a', 'a|c']).str.get_dummies()
   a  b  c
0  1  1  0
1  1  0  0
2  1  0  1
>>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()
   a  b  c
0  1  1  0
1  0  0  0
2  1  0  1
  • partition(pat='', expand=True): 第一次出现pat时将字符串分割为三个部分: pat前面的部分, pat本身, pat后面的部分
  • rpartition(): 从右往左检测pat字符串

更新字符串

  • replace(): 更新字符串
参数 说明
pat 字符串或编译的正则表达式
repl str: 将匹配到的字符串替换为此字符串
fun: 传给fun的是对象相当于re.search(pat, string)的返回值
n=-1 替换的次数, 默认全部
case=None 是否区分大小写, 如果pat为字符串则默认为True, 若为编译的正则表达式则不能设置
flags=0 可传入re.IGNORECASE之类的参数, 但若pat为编译的正则表达式则不能设置
  • slice_replace(): 将选中的部分替换为指定字符串
参数 说明
start=None 开始位置
stop=None 结束位置
repl=None 要替换为的字符串
  • translate(): 字符替换
    1. dict: {ord('a'): 'x'} 或 {ord('a'): ord('x')} key必须是ascii码, value可以是字符串或ASCII码
    2. str.maketrans('a','x') 等同于 {97: 120}
原文地址:https://www.cnblogs.com/P--K/p/11148250.html