Index([' Columns A', ' Columns B'], dtype='object')
Index(['-Columns-A', '--Columns-B'], dtype='object')
Index(['heheColumns-A', 'hehe-Columns-B'], dtype='object')
#字符串常用方法 - split、rsplit 分成列表list的形式
s = pd.Series(['a,b,c','1,2,3',['a,,,c'],np.nan])
print(s)
print('----')
print(s.str.split(','))
print('----')
#类似于字符串的split
print(s.str.split(',')[0])#索引第一行
print(s.str.split(',').str[0])#第一列
print(s.str.split(',').str.get(1))#第二列
#可以使用get或者[]符号访问拆分列表的元素
print(s.str.split(',',expand=True,n=1))#n为拓展数量
print(s.str.rsplit(',',expand=True,n=1))#rsplit 从右到左分
#expand可以扩展此操作来返回DataFrame
#n参数限制分数
#rsplit类似于split,反向工作,即从字符串的末尾到字符串开头
print('dataframe:')
df = pd.DataFrame({'key1':['a,b,c','1,2,3',[',,,']],
'key2':['a-b-c','1-2-c',[',-,-,']]})
print(df['key2'])
print(df['key2'].str.split('-'))
结果:
0 a,b,c
1 1,2,3
2 [a,,,c]
3 NaN
dtype: object
----
0 [a, b, c]
1 [1, 2, 3]
2 NaN
3 NaN
dtype: object
----
['a', 'b', 'c']
0 a
1 1
2 NaN
3 NaN
dtype: object
0 b
1 2
2 NaN
3 NaN
dtype: object
0 1
0 a b,c
1 1 2,3
2 NaN NaN
3 NaN NaN
0 1
0 a,b c
1 1,2 3
2 NaN NaN
3 NaN NaN
dataframe:
0 a-b-c
1 1-2-c
2 [,-,-,]
Name: key2, dtype: object
0 [a, b, c]
1 [1, 2, c]
2 NaN
Name: key2, dtype: object
#字符串索引
s = pd.Series(['A','b','C','bbhello','123',np.nan,'hj'])
df = pd.DataFrame({'key1':list('abcdef'),
'key2':['hee','fv','w','hjja','123',np.nan]})
print(s,'\n-----')
print(s.str[0])#取第一个字符串
print(s.str[:2])#取前2个字符
print('-----')
print(df['key2'].str[0])
#str之后和字符串本身索引方式相同
结果:
0 A
1 b
2 C
3 bbhello
4 123
5 NaN
6 hj
dtype: object
-----
0 A
1 b
2 C
3 b
4 1
5 NaN
6 h
dtype: object
0 A
1 b
2 C
3 bb
4 12
5 NaN
6 hj
dtype: object
-----
0 h
1 f
2 w
3 h
4 1
5 NaN
Name: key2, dtype: object