# 通过str访问,且自动排除丢失/ NA值
s = pd.Series(['A','b','C','bbhello','123',np.nan,'hj'])
[output]:
0 A
1 b
2 C
3 bbhello
4 123
5 NaN
6 hj
dtype: object
s.str.count('b')
[output]:
0 0.0
1 1.0
2 0.0
3 2.0
4 0.0
5 NaN
6 0.0
dtype: float64
df = pd.DataFrame({'key1':list('abcdef'),
'key2':['hee','fv','w','hija','123',np.nan]})
[output]:
key1 key2
0 a hee
1 b fv
2 c w
3 d hija
4 e 123
5 f NaN
df['key2'].str.upper()
[output]:
0 HEE
1 FV
2 W
3 HIJA
4 123
5 NaN
Name: key2, dtype: object
df.columns = df.columns.str.upper()
[output]:
KEY1 KEY2
0 a hee
1 b fv
2 c w
3 d hija
4 e 123
5 f NaN
# 字符串常用方法(1) - lower,upper,len,startswith,endswith
s = pd.Series(['A','b','bbhello','123',np.nan])
print(s.str.lower(),'→ lower小写\n')
print(s.str.upper(),'→ upper大写\n')
print(s.str.len(),'→ len字符长度\n')
print(s.str.startswith('b'),'→ 判断起始是否为a\n')
print(s.str.endswith('3'),'→ 判断结束是否为3\n')
# 字符串常用方法(2) - strip
s = pd.Series([' jack', 'jill ', ' jesse ', 'frank'])
df = pd.DataFrame(np.random.randn(3, 2), columns=[' Column A ', ' Column B '],
index=range(3))
print(s)
print(df)
print('-----')
print(s.str.strip()) # 去除字符串中的空格
print(s.str.lstrip()) # 去除字符串中的左空格
print(s.str.rstrip()) # 去除字符串中的右空格
df.columns = df.columns.str.strip()
print(df)
# 这里去掉了columns的前后空格,但没有去掉中间空格
# 字符串常用方法(3) - replace
df = pd.DataFrame(np.random.randn(3, 2), columns=[' Column A ', ' Column B '],
index=range(3))
df.columns = df.columns.str.replace(' ','-')
print(df)
# 替换
df.columns = df.columns.str.replace('-','hehe',n=1)
print(df)
# n:替换个数
[output]:
-Column-A- -Column-B-
0 1.855227 -0.519479
1 -0.400376 -0.421383
2 -0.293797 -0.432481
heheColumn-A- heheColumn-B-
0 1.855227 -0.519479
1 -0.400376 -0.421383
2 -0.293797 -0.432481
# 字符串常用方法(4) - split、rsplit
s = pd.Series(['a,b,c','1,2,3',['a,,,c'],np.nan])
[output]:
0 a,b,c
1 1,2,3
2 [a,,,c]
3 NaN
dtype: object
s.str.split(',')
[output]:
0 [a, b, c]
1 [1, 2, 3]
2 NaN
3 NaN
dtype: object
s.str.split(',')[0]
[output]:
['a', 'b', 'c']
s.str.split(',').str[0]
s.str.split(',').str.get(0)
[output]:
0 a
1 1
2 NaN
3 NaN
dtype: object
s.str.split(',', expand=True)
[output]:
0 1 2
0 a b c
1 1 2 3
2 NaN NaN NaN
3 NaN NaN NaN
s.str.rsplit(',', expand=True, n = 1)
s.str.split(',', expand=True, n = 1)
# 可以使用expand可以轻松扩展此操作以返回DataFrame
# n参数限制分割数
# rsplit类似于split,反向工作,即从字符串的末尾到字符串的开头
df = pd.DataFrame({'key1':['a,b,c','1,2,3',[':,., ']],
'key2':['a-b-c','1-2-3',[':-.- ']]})
key1 key2
0 a,b,c a-b-c
1 1,2,3 1-2-3
2 [:,., ] [:-.- ]
df['key2'].str.split('-')
0 [a, b, c]
1 [1, 2, 3]
2 NaN
Name: key2, dtype: object
# 字符串常用方法(5)-- 字符串索引
s = pd.Series(['A','b','C','bbhello','123',np.nan,'hj'])
[output]:
0 A
1 b
2 C
3 bbhello
4 123
5 NaN
6 hj
dtype: object
print(s.str[0]) # 取第一个字符串
[output]:
0 A
1 b
2 C
3 b
4 1
5 NaN
6 h
dtype: object
print(s.str[:2]) # 取前两个字符串
df = pd.DataFrame({'key1':list('abcdef'),
'key2':['hee','fv','w','hija','123',np.nan]})
[output]:
key1 key2
0 a hee
1 b fv
2 c w
3 d hija
4 e 123
5 f NaN
print(df['key2'].str[0])
# str之后和字符串本身索引方式相同
0 h
1 f
2 w
3 h
4 1
5 NaN
Name: key2, dtype: object