文章目录

  • 1.简介
  • 2. 示例代码
  • 2.1 小试一刀
  • 2.2 pandas 字符串方法列表
  • 2.3 pandas 字符串向量化操作支持正则表达式
  • 2.4 其它字符串方法

1.简介

  1. 使用numpy与pandas 对数组元素进行操作,向量化操作简化了纯数值的数组操作语法–无需关注数据长度或维度,只关心需要的操作

2. 示例代码

2.1 小试一刀

Administrator@cibpc-019 MINGW64 /
$ ipython
Python 3.6.7 (default, Jul  2 2019, 02:21:41) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import numpy as np

In [2]: import pandas as pd
# 示例数据(常规数据)
In [3]: data = ['peter', 'Paul', 'MARY', 'GuiDO']
# 数据值正常时的操作方法
In [4]: [s.capitalize() for s in data]
Out[4]: ['Peter', 'Paul', 'Mary', 'Guido']
# 实际上, 这才是我们经常碰到的常规数据, 对吧? :)
In [5]: data = ['peter', 'Paul', 'MARY', 'GuiDO', None]
# 这种处理方法就不太友好了
In [6]: [s.capitalize() for s in data]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-bb1b424b25b0> in <module>
----> 1 [s.capitalize() for s in data]

<ipython-input-6-bb1b424b25b0> in <listcomp>(.0)
----> 1 [s.capitalize() for s in data]

AttributeError: 'NoneType' object has no attribute 'capitalize'

In [7]: names = pd.Series(data)

In [8]: names
Out[8]:
0    peter
1     Paul
2     MARY
3    GuiDO
4     None
dtype: object
# 这是正经的向量化字符串操作, 有没有很6. 只需要关注操作的方法即可, 不用操心异常数值.
In [9]: names.str.capitalize()
Out[9]:
0    Peter
1     Paul
2     Mary
3    Guido
4     None
dtype: object

2.2 pandas 字符串方法列表

  • 在pandas中, 可以对字符串进行向量化操作的方法都有哪些呢?
    len() lower() translate() islower()ljust() upper() startswith() isupper()rjust() find() endswith() isnumeric()center() rfind() isalnum() isdecimal()zfill() index() isalpha() split()strip() rindex() isdigit() rsplit()rstrip() capitalize() isspace() partition()lstrip() swapcase() istitle() rpartition()
  • 2.2.1 代码示例
In [10]: monte = pd.Series(['Graham Chapman', 'John Cleese', 'Terry Gilliam', 'Eric idle'])

In [11]: monte
Out[11]:
0    Graham Chapman
1       John Cleese
2     Terry Gilliam
3         Eric idle
dtype: object
# 返回全小写
In [12]: monte.str.lower()
Out[12]:
0    graham chapman
1       john cleese
2     terry gilliam
3         eric idle
dtype: object
# 返回int型
In [13]: monte.str.len()
Out[13]:
0    14
1    11
2    13
3     9
dtype: int64
# 返回布尔型
In [14]: monte.str.startswith('T')
Out[14]:
0    False
1    False
2     True
3    False
dtype: bool
# 返回list
In [15]: monte.str.split()
Out[15]:
0    [Graham, Chapman]
1       [John, Cleese]
2     [Terry, Gilliam]
3         [Eric, idle]
dtype: object

2.3 pandas 字符串向量化操作支持正则表达式

  • 2.3.1 pandas 支持正则表达式操作与python的re 模块相通, 关系如下:

方法

描述

match()

对每个元素调用re.match(), 返回布尔类型值

extract()

对每个元素调用re.match(), 返回匹配的字符串组(groups)

findall()

对每个元素调用re.findall()

replace()

用正则模式替换字符串

contains()

对每个元素调用re.search(), 返回布尔类型值

count()

计算符合正则模式的字符串的数量

split()

等价于str.split(), 支持正则表达式

rsplit()

等价于str.rsplit(), 支持正则表达式

  • 2.3.2 代码示例
In [16]: monte.str.extract('([A-Za-z]+)')
Out[16]:
        0
0  Graham
1    John
2   Terry
3    Eric

In [17]: monte.str.findall(r'^[^AEIOU].*[^aeiou]$')
Out[17]:
0    [Graham Chapman]
1                  []
2     [Terry Gilliam]
3                  []
dtype: object

2.4 其它字符串方法

  • 2.4.1 方法列表

方法

描述

get()

获取元素索引位置上的值, 索引从0开始

slice()

对元素进行切片取值

slice_replace()

对元素进行切片替换

cat()

连接字符串

repeat()

重复元素

normalize()

将字符串转换为Unicode规范形式

pad()

在字符串的左边\ 右边或两边增加空格

wrap()

将字符串按指定宽度换行

join()

用分隔符连接Series的每个元素

get_dummies()

按照分隔符提取每个元素的dummy变量, 转换为独热(one-hot)编码的DataFrame

  • 2.4.2 代码示例
In [18]: monte.str[:3]
Out[18]:
0    Gra
1    Joh
2    Ter
3    Eri
dtype: object
# 这两种等效
In [19]: monte.str.slice(0, 3)
Out[19]:
0    Gra
1    Joh
2    Ter
3    Eri
dtype: object

In [20]: monte.str.get(3)
Out[20]:
0    h
1    n
2    r
3    c
dtype: object
# 这两种操作方法等效
In [21]: monte.str[3]
Out[21]:
0    h
1    n
2    r
3    c
dtype: object

# 综合运用
In [22]: monte.str.split().str.get(-1)
Out[22]:
0    Chapman
1     Cleese
2    Gilliam
3       idle
dtype: object