結果: 0 jack 1 jill 2 jease 3 feank dtype: object Index([' Column A', ' Column B'], dtype='object') ['jack ' 'jill' 'jease ' 'feank'] [' jack' 'jill' ' ...
import numpy as np
import pandas as pd
1 #字元串常用方法 - strip 2 s = pd.Series([' jack ','jill',' jease ','feank']) 3 df = pd.DataFrame(np.random.randn(3,2),columns=[' Column A',' Column B'],index=range(3)) 4 print(s) 5 print(df.columns) 6 7 print('----') 8 print(s.str.lstrip().values)#去掉左邊的空格 9 print(s.str.rstrip().values)#去掉右邊的空格 10 df.columns = df.columns.str.strip() 11 print(df.columns)
結果:
0 jack 1 jill 2 jease 3 feank dtype: object Index([' Column A', ' Column B'], dtype='object') ---- ['jack ' 'jill' 'jease ' 'feank'] [' jack' 'jill' ' jease' 'feank'] Index(['Column A', 'Column B'], dtype='object')
#字元串常用方法 - replace 替換字元串 df = pd.DataFrame(np.random.randn(3,2),columns=[' Columns A',' Columns B'],index = range(3)) print(df.columns) df.columns = df.columns.str.replace(' ','-') print(df.columns) df.columns = df.columns.str.replace('-','hehe',n=1)#表示用hehe去替換第一個' ' print(df.columns)
結果:
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