本文共 9576 字,大约阅读时间需要 31 分钟。
str函数 2018/12/22
简单介绍正则表达式,详细见本人博文;
矢量化字符串方法介绍;包括正则表达式匹配查找,提取字符,分裂,连接,索引及元素提取。
str分裂;国际字符的转换。
1.函数表
矢量化字符串方法 | |||
No | 方法 | RE | 说明 |
0 | 使用方式:s.str.cat() | 返回序列索引或其他 | |
1 | capitalize() | no | 字符串转大写 |
2 | cat([others, sep, na_rep, join]) | no | 用分隔符连接字符串;返回str或原对象构架 |
3 | center(width[, fillchar]) | no | 用附加字符填充字符串的左侧和右侧 |
4 | contains(‘'is') | yes | 判断字符串中是否包含子串true; pat str或正则表达式 |
5 | count(pat[, flags]) | yes | 子串出现次数 |
6 | decode(encoding[, errors]) | no | 字节解码 |
7 | encode(encoding[, errors]) | no | 字符串编码 |
8 | endswith(pat[, na]) | yes | 字符串结尾是否是特定子串 true |
9 | extract(pat[, flags, expand]) | yes | 从正则表达式pat中提取第一个匹配字符;结果为1个字符 |
10 | extractall(pat[, flags]) | yes | 从正则表达式pat提取所有匹配的,返回组 |
11 | find(sub[, start, end]) | no | 查子串首索引,子串包含在[start:end];无返回-1 |
12 | findall(pat[, flags]) | yes | 查找所有符合正则表达式的字符,以数组形式返回 |
13 | get(i) | no | 从指定位置提取字符 |
14 | get_dummies([sep]) | no | 用sep拆分每个字符串,返回一个虚拟/指示dataFrame |
15 | index(sub[, start, end]) | no | 子串最低索引,子串范围[start:end];无抛异常ValueError |
16 | isalnum() | no | 检查所有字符是否为字母数字 |
17 | isalpha() | no | 检查是否都是字母 |
18 | isdecimal() | no | 检查是否都是十进制 |
19 | isdigit() | no | 检查是否都是数字 |
20 | islower() | no | 检查是否都是小写 |
21 | isnumeric() | no | 检查是否都是数字 |
22 | isspace() | no | 检查是否都是空格 |
23 | istitle() | no | 检查是否都是标题 |
24 | isupper() | no | 检查是否都是大写 |
25 | join(sep) | no | 用分隔符连接所有字符;同一级有非str返回Na |
26 | len() | no | 计算每个字符串的长度 |
27 | ljust(width[, fillchar]) | no | 使用附加字符填充字符串的右侧 |
28 | lower() | no | 字符串转小写 |
29 | lstrip([to_strip]) | no | 左侧删除空格(包括换行符)或其他str |
30 | match(pat[, case, flags, na, …]) | yes | 确定每个字符串是否与正则表达式匹配。 |
31 | normalize(form) | no | 返回字符串的Unicode普通表单 |
32 | pad(width[, side, fillchar]) | no | 指定左或右填充字符补齐字符串 |
33 | partition([pat, expand]) | no | 分隔符拆分为3部分,分隔符左,分隔符,分隔符右 |
34 | repeat(repeats) | no | 重复每个元素指定的次数 |
35 | replace(pat,b) | yes | 将值pat替换为值b。 |
36 | rfind(sub[, start, end]) | no | 右边查找子串索引,子串包含在[start:end];无返回-1 |
37 | rindex(sub[, start, end]) | no | 返回子串的最高索引,子串范围[start:end];无抛出异常 |
38 | rjust(width[, fillchar]) | no | 使用附加字符填充字符串的左侧 |
39 | rpartition([pat, expand]) | no | 右拆分成3部分含分隔符 |
40 | rsplit([pat, n, expand]) | yes | 分隔符字符串右边拆分字符串 |
41 | rstrip([to_strip]) | no | 右侧删除空格(包括换行符) |
42 | slice([start, stop, step]) | no | 切片截取字符串 |
43 | slice_replace([start, stop, repl]) | no | 用另一个值替换字符串的位置切片;比较复杂看实例 |
44 | split([pat=None, n, expand]) | yes | 按分隔符或子串拆分字符串 |
45 | startswith('st') | yes | 字符串开头是否匹配子串True |
46 | strip('') | no | 删除字符串左右空白(包括换行符)或删除其他左右字符串 |
47 | swapcase() | no | 变换字母大小写 |
48 | title() | no | 字符串转标题 |
49 | translate(table[, deletechars]) | no | 通过映射表映射字符串中的所有字符 |
50 | upper() | no | 字符串转大写 |
51 | wrap(width, **kwargs) | no | 长字符串换行,#结果插入换行符\n |
52 | zfill(width) | no | 用0填充字符串的左侧 |
说明:类似Python中str忽略Na;适用于Series / Index |
2矢量化字符串操作
2.1检测字符串是否包含某字符模式或者匹配它
实现矢量化的元素获取操作data.map 所有str和正则表达式方法都能被用于(传入lambda表达式或其他函数)各个值,存在NA就会报错
# 实例1:查找匹配字符串s=pd.Series(['a1','A2','ab3',np.nan,'a4@d']) s.str.contains(r'[a-z][0-9]') # 检测数据中包含一个字母和一个数字s[s.str.contains(r'[a-z][0-9]',na=False)] # na参数规定出现NaN数据时匹配成Falses.str.match(r'[a-z][0-9]',as_indexer=False) # 严格匹配字符串s[s.notna()].str.findall("^[a-z]*[0-9]*$") # 输出1: 输出2: 输出3: 输出4:# 0 True 0 a1 0 True 0 [a1]# 1 False 2 ab3 1 False 1 []# 2 True 4 a4@d 2 False 2 [ab3]# 3 NaN dtype: object 3 NaN 4 []# 4 True 4 True
2.2匹配开始结尾
# 实例2:匹配开始s.str.startswith('a',na=False) # 查找以字母a开头的数据s.str.contains(r'^a',na=False) # 查找以字母a开头的数据# 实例3:匹配结尾s.str.endswith('1',na=False) # 检查结束字符串s.str.contains('1$',na=False)# 检查结束字符串
#实例2:输出 实例3:输出# 0 True 0 True# 1 False 1 False# 2 True 2 False# 3 False 3 False# 4 True 4 False
2.3抽取匹配字符串:注意要加上括号
s[s.notna()].str.extract("(^[a-z]*[0-9]*$)")# 0# 0 a1# 1 NaN# 2 ab3# 4 NaN
2.4拆分
s=pd.Series("this is ".split()) # this , iss[s.notna()].str.split("([@])") #分组s[s.notna()].str.split("[@]")# 输出1: 输出2:# 0 [a1] 0 [a1]# 1 [A2] 1 [A2]# 2 [ab3] 2 [ab3]# 4 [a4, @, d] 4 [a4, d]
2.5字符串连接
s1 = pd.Series([['Tom', 'Bob', 'Jim'], [1.1, 2.2, 3.3], ['s1', np.nan, 's2'],['s3', 4.5, 's4'], ['s5', ['s6', 's7'], 's8']])s1.str.join('-')s.str.join('-')# s1 #输出1: #输出2:# 0 [Tom, Bob, Jim] # 0 Tom-Bob-Jim # 0 a-1# 1 [1.1, 2.2, 3.3] # 1 NaN # 1 A-2# 2 [s1, nan, s2] # 2 NaN # 2 a-b-3# 3 [s3, 4.5, s4] # 3 NaN # 3 NaN# 4 [s5, [s6, s7], s8] # 4 NaN # 4 a-4-@-d
2.5字符串连接
s=pd.Series(['a','b',np.nan,'d'])t = pd.Series(['D', 'A', 'B', 'C'], index=[4, 1, 2, 3])s.str.cat(['A', 'B', 'C', 'D'], sep=',')s.str.cat(['A', 'B', 'C', 'D'], sep=',', na_rep='-')s.str.cat(t, join=None, na_rep='-')s.str.cat(t, join='left', na_rep='-')s.str.cat(t, join='outer', na_rep='-')s.str.cat(t, join='inner', na_rep='-')s.str.cat(t, join='right', na_rep='-')#输出1: 输出2: 输出3: 输出4: 输出5: 输出6: 输出7:# 0 a,A # 0 a,A # 0 aD # 0 a- # 0 a- # 1 bA # 4 -D# 1 b,B # 1 b,B # 1 bA # 1 bA # 1 bA # 2 -B # 1 bA# 2 NaN # 2 -,C # 2 -B # 2 -B # 2 -B # 3 dC # 2 -B# 3 d,D # 3 d,D # 3 dC # 3 dC # 3 dC # # 3 dC
2.6字符串替换:
s = pd.Series(['a', 'ab', 'abc', 'abdc', 'abcde'])s.str.slice_replace(1, repl='X') # start参数:将start-结尾全部替换替换为“repl"s.str.slice_replace(stop=2, repl='X') # stop’参数:str开头替换为‘Stop’,其余不变s.str.slice_replace(start=1, stop=3, repl='X')# 从start -stop’片段内替换为‘repl’,其他不变# s 输出1: 输出2: 输出3:# 0 a # 0 aX # 0 X # 0 aX# 1 ab # 1 aX # 1 X # 1 aX# 2 abc # 2 aX # 2 Xc # 2 aX# 3 abdc # 3 aX # 3 Xdc # 3 aXc# 4 abcde # 4 aX # 4 Xcde # 4 aXde
2.7实例:索引
s=pd.Series(['a1','A2','ab3',np.nan,'a4@d'])
s[s.str.contains(r'3',na=False)].str.index('3') #当子串不存在出错ValueError#2s[s.str.contains(r'3',na=False)].str.find('3') #2s[s.str.contains(r'3',na=False)].str.find('!') #-1
2.8实例:编码解码
v=s.str.encode('utf-8')v.str.decode('utf-8')#输出1: 输出2:# 0 b'a1' 0 a1# 1 b'A2' 1 A2# 2 b'ab3' 2 ab3# 3 NaN 3 NaN# 4 b'a4@d' 4 a4@d
2.9实例2:translate字符串映射表
intab='aeiou'outtab='12345'trantab=str.maketrans(intab,outtab) # {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}s=pd.Series('this is')s.str.translate(trantab)# 0 th3s 3s# dtype: object
2.10获取元素:
s = pd.Series(["String",(1, 2, 3), ["a", "b", "c"],123, -456,{1:"Hello", "2":"World"}])s.str.get(1)pd.Series(['a|b', 'a', 'a|c']).str.get_dummies()pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()# s 输出1: 输出2: 输出3:# 0 String 0 t a b c a b c# 1 (1, 2, 3) 1 2 0 1 1 0 0 1 1 0# 2 [a, b, c] 2 b 1 1 0 0 1 0 0 0# 3 123 3 NaN 2 1 0 1 2 1 0 1# 4 -456 4 NaN # 5 {1: 'Hello', '2': 'World'} 5 Hello
3.正则表达式
3.1函数:
方法 | 说明 | |
findall | 返回匹配字符串组成的列表 | |
finditer | 返回匹配字符串的迭代器 | |
match | 匹配字符串起始位置;返回匹配或None | |
search | 匹配字符串中的一个位置;返回匹配或None | |
split | 根据找到的模式将字符拆分为数段 | |
sub | 将字符串中匹配的替换为指定子串 | |
subn | 将字符串中匹配的替换为指定子串;返回匹配数量 |
3.2实例:
# re模块的函数可以分为三个大类:模式匹配、替换以及拆分# 实例1:text ='foo bar\t baz \tqux're.split('\s+', text)# [ 'foo ', 'bar ', 'baz ', 'qux']regex = re.compile( '\s+')regex.split(text) #['foo', 'bar', 'baz', 'qux']regex.findall(text) #匹配regex的所有模式 # [' ', '\t ', ' \t']# 实例2:text =r'Tom Tom@google.com Rob rob@gmail.com'pattern= r'[A-Z0-9_]+@[A-Z0-9]*\.[A-Z0-9]{2,3}'regex = re.compile(pattern,flags=re.I)#re.I大小写不敏感regex.findall(text) # ['Tom@google.com', 'rob@gmail.com']text [m. start():m.end()] #模式在原字符串中的起始和结束位置# 'Tom@google.com'regex.sub('No', text) #将匹配到的模式替换为指定字符串 'Tom No Rob No'# 实例3:分组pattern= r'([A-Z0-9_]+)@([A-Z0-9_]+)\.([A-Z]{2,4})'regex = re.compile(pattern, flags=re.IGNORECASE)m = regex.match('Tom@city.net')#只匹配出现在学符串开头的模式m.groups() #('Tom', 'city', 'net')regex.findall('Tom@city.net') # [('Tom', 'city', 'net')]regex.sub(r'Username=\1,city=\2,remark=\3','Tom@city.net')# 'Username=Tom,city=city,remark=net'# 实例4:regex = re.compile(r''' (?P[A-Z0-9_]+) @ (?P [A-Z0-9_]+) \. (?P [A-Z]{2,4}) ''', flags=re.IGNORECASE | re.VERBOSE)m = regex.match('Tom@city.net')m.groupdict() #{'username': 'Tom', 'city': 'city', 'remark': 'net'}
4.str函数实例1:
val= ' a,b, guido 'pieces=val.strip().split(',') #删除空白符,逗号分隔# ['a', 'b', 'guido']first, second, third = pieces%timeit first+ ':’ + second + ’:' + third#连接 # 299 ns%timeit ':'.join(pieces) #连接 # 201 nsval.replace(',',':') #替换 为空等于删除 #' a:b: guido '
实例2:
unicodedata.normalize(form,unistr )# 返回Unicode字符串unistr的普通表单表单。# 表单的有效值为 “NFC”,“NFKC”,“NFD”和“NFKD”。# 正规形式D(NFD)也称为规范分解,并将每个字符转换为其分解形式。# 普通形式C(NFC)首先应用规范分解,然后再次组合预组合字符。# 普通形式KD(NFKD)将应用兼容性分解,即将所有兼容性字符替换为其等效字符。# 正常形式KC(NFKC)首先应用兼容性分解,然后是规范组合物。import unicodedataunicodedata.normalize('NFD', '\u00C7').encode('utf-8')# 'Ç'unicodedata.normalize('NFD', '\u0043') # 'C'unicodedata.normalize('NFD', '\u0327') # '̧'unicodedata.normalize('NFD', '\u0043\u0327') # 'Ç'unicodedata.normalize('NFD', '\u00C7').encode('ascii','ignore')#b'C'b1=unicodedata.normalize('NFD', '\u00C7').encode('ascii','ignore')b1.decode() # 'C'title = u"Klüft skräms inför på fédéral électoral große"unicodedata.normalize('NFKD', title).encode('ascii','ignore') # 'Kluft skrams infor pa federal electoral groe'
转载地址:http://pfqbf.baihongyu.com/