You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.6 KiB

3.2.7:字符串操作方法

字符串方法

如果你对Python字符串方法十分了解,那么下面的知识对你来说如瓮中捉鳖,几乎所有的Python内置的字符串方法都被复制到Pandas的向量化字符串方法中。下图列举了Pandasstr方法借鉴Python字符串方法的内容:


它们的作用与Python字符串的基本一致,但是需要注意这些方法的返回值不同。举两个例子:

monte = pd.Series(['Graham Chapman', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones', 'Michael Palin'])
monte.str.lower()  # 返回字符串

输出:

 0 graham chapman 
 1    john cleese 
 2  terry gilliam 
 3      eric idle 
 4    terry jones 
 5  michael palin 
 dtype: object
monte.str.split()  # 返回列表

输出:

 0   [Graham, Chapman] 
 1   [John, Cleese] 
 2   [Terry, Gilliam] 
 3   [Eric, Idle] 
 4   [Terry, Jones] 
 5   [Michael, Palin] 
 dtype: object

pandas中还有一些自带的字符串方法,如下图所示:

其中get_dummies()方法有点难以理解,给大家举个例子,假设有一个包含了某种编码信息的数据集,如 A= 出生在美国、B= 出生在英国、C= 喜欢奶酪、D= 喜欢午餐肉:

full_monte = pd.DataFrame({
 'name': monte,
 'info': ['B|C|D', 'B|D', 'A|C', 'B|D', 'B|C', 'B|C|D']})
print(full_monte)

输出:

    info    name 
 0 B|C|D   Graham Chapman 
 1 B|D     John Cleese 
 2 A|C     Terry Gilliam 
 3 B|D     Eric Idle 
 4 B|C     Terry Jones 
 5 B|C|D   Michael Palin

get_dummies()方法可以让你快速将这些指标变量分割成一个独热编码的DataFrame(每个元素都是01

full_monte['info'].str.get_dummies('|') 

输出:

   A B C D 
 0 0 1 1 1 
 1 0 1 0 1 
 2 1 0 1 0 
 3 0 1 0 1 
 4 0 1 1 0 
 5 0 1 1 1

正则表达式方法

还有一些支持正则表达式的方法可以用来处理每个字符串元素。如下图所示:

众所周知,正则表达式“无所不能”,我们可以利用正则实现一些独特的操作,例如提取每个人的first name

monte.str.extract('([A-Za-z]+)')

输出:

0  Graham 
1  John 
2  Terry 
3  Eric 
4  Terry
5  Michael 
dtype: object

或者找出所有开头和结尾都是辅音字符的名字:

monte.str.findall(r'^[^AEIOU].*[^aeiou]$')

输出:

0 [Graham Chapman] 
1 [] 
2 [Terry Gilliam] 
3 [] 
4 [Terry Jones] 
5 [Michael Palin] 
dtype: object