Python pandas 資料框的str列內建的方法詳解__Python
來源:互聯網
上載者:User
原文連結:http://www.datastudy.cc/to/27
在使用pandas架構的DataFrame的過程中,如果需要處理一些字串的特性,例如判斷某列是否包含一些關鍵字,某列的字元長度是否小於3等等這種需求,如果掌握str列內建的方法,處理起來會方便很多。
下面我們來詳細瞭解一下,Series類的str內建的方法有哪些。
1、cat() 拼接字串 例子: >>> Series(['a', 'b', 'c']).str.cat(['A', 'B', 'C'], sep=',') 0 a,A 1 b,B 2 c,C dtype: object >>> Series(['a', 'b', 'c']).str.cat(sep=',') 'a,b,c' >>> Series(['a', 'b']).str.cat([['x', 'y'], ['1', '2']], sep=',') 0 a,x,1 1 b,y,2 dtype: object 2、split() 切分字串 >>> import numpy,pandas; >>> s = pandas.Series(['a_b_c', 'c_d_e', numpy.nan, 'f_g_h']) >>> s.str.split('_') 0 [a, b, c] 1 [c, d, e] 2 NaN 3 [f, g, h] dtype: object >>> s.str.split('_', -1) 0 [a, b, c] 1 [c, d, e] 2 NaN 3 [f, g, h] dtype: object >>> s.str.split('_', 0) 0 [a, b, c] 1 [c, d, e] 2 NaN 3 [f, g, h] dtype: object >>> s.str.split('_', 1) 0 [a, b_c] 1 [c, d_e] 2 NaN 3 [f, g_h] dtype: object >>> s.str.split('_', 2) 0 [a, b, c] 1 [c, d, e] 2 NaN 3 [f, g, h] dtype: object >>> s.str.split('_', 3) 0 [a, b, c] 1 [c, d, e] 2 NaN 3 [f, g, h] dtype: object 3、get() 擷取指定位置的字串 >>> s.str.get(0) 0 a 1 c 2 NaN 3 f dtype: object >>> s.str.get(1) 0 _ 1 _ 2 NaN 3 _ dtype: object >>> s.str.get(2) 0 b 1 d 2 NaN 3 g dtype: object 4、join() 對每個字元都用給點的字串拼接起來,不常用 >>> s.str.join("!") 0 a!_!b!_!c 1 c!_!d!_!e 2 NaN 3 f!_!g!_!h dtype: object >>> s.str.join("?") 0 a?_?b?_?c 1 c?_?d?_?e 2 NaN 3 f?_?g?_?h dtype: object >>> s.str.join(".") 0 a._.b._.c 1 c._.d._.e 2 NaN 3 f._.g._.h dtype: object 5、contains() 是否包含運算式 >>> s.str.contains('d') 0 False 1 True 2 NaN 3 False dtype: object 6、replace() 替換 >>> s.str.replace("_", ".") 0 a.b.c 1 c.d.e 2 NaN 3 f.g.h dtype: object 7、repeat() 重複 >>> s.str.repeat(3) 0 a_b_ca_b_ca_b_c 1 c_d_ec_d_ec_d_e 2 NaN 3 f_g_hf_g_hf_g_h dtype: object 8、pad() 左右補齊 >>> s.str.pad(10, fillchar="?") 0 ?????a_b_c 1 ?????c_d_e 2 NaN 3 ?????f_g_h dtype: object >>> >>> s.str.pad(10, side="right", fillchar="?") 0 a_b_c?????