2018.03.26 Python-Pandas 字串常用方法,
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 jill2 jease 3 feankdtype: objectIndex([' 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('----')#類似於字串的splitprint(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 A1 b2 C3 bbhello4 1235 NaN6 hjdtype: object -----0 A1 b2 C3 b4 15 NaN6 hdtype: object0 A1 b2 C3 bb4 125 NaN6 hjdtype: object-----0 h1 f2 w3 h4 15 NaNName: key2, dtype: object