三、文本处理的五类操作

1. 拆分

str.split 能够把字符串的列进行拆分,其中第一个参数为正则表达式,可选参数包括从左到右的最大拆分次数 n ,是否展开为多个列 expand

In [42]: s = pd.Series(['上海市黄浦区方浜中路249号',
   ....:             '上海市宝山区密山路5号'])
   ....: 
In [43]: s.str.split('[市区路]')
Out[43]: 
0    [上海, 黄浦, 方浜中, 249号]
1       [上海, 宝山, 密山, 5号]
dtype: object
In [44]: s.str.split('[市区路]', n=2, expand=True)
Out[44]: 
    0   1         2
0  上海  黄浦  方浜中路249号
1  上海  宝山     密山路5号

与其类似的函数是 str.rsplit ,其区别在于使用 n 参数的时候是从右到左限制最大拆分次数。但是当前版本下 rsplit 因为 bug 而无法使用正则表达式进行分割:

In [45]: s.str.rsplit('[市区路]', n=2, expand=True)
Out[45]: 
                0
0  上海市黄浦区方浜中路249号
1     上海市宝山区密山路5号

2. 合并

关于合并一共有两个函数,分别是 str.joinstr.catstr.join 表示用某个连接符把 Series 中的字符串列表连接起来,如果列表中出现了非字符串元素则返回缺失值:

In [46]: s = pd.Series([['a','b'], [1, 'a'], [['a', 'b'], 'c']])
In [47]: s.str.join('-')
Out[47]: 
0    a-b
1    NaN
2    NaN
dtype: object

str.cat 用于合并两个序列,主要参数为连接符 sep 、连接形式 join 以及缺失值替代符号 na_rep ,其中连接形式默认为以索引为键的左连接。

In [48]: s1 = pd.Series(['a','b'])
In [49]: s2 = pd.Series(['cat','dog'])
In [50]: s1.str.cat(s2,sep='-')
Out[50]: 
0    a-cat
1    b-dog
dtype: object
In [51]: s2.index = [1, 2]
In [52]: s1.str.cat(s2, sep='-', na_rep='?', join='outer')
Out[52]: 
0      a-?
1    b-cat
2    ?-dog
dtype: object

3. 匹配

str.contains 返回了每个字符串是否包含正则模式的布尔序列:

In [53]: s = pd.Series(['my cat', 'he is fat', 'railway station'])
In [54]: s.str.contains('\s\wat')
Out[54]: 
0     True
1     True
2    False
dtype: bool

str.startswithstr.endswith 返回了每个字符串以给定模式为开始和结束的布尔序列,它们都不支持正则表达式:

In [55]: s.str.startswith('my')
Out[55]: 
0     True
1    False
2    False
dtype: bool
In [56]: s.str.endswith('t')
Out[56]: 
0     True
1     True
2    False
dtype: bool

如果需要用正则表达式来检测开始或结束字符串的模式,可以使用 str.match ,其返回了每个字符串起始处是否符合给定正则模式的布尔序列:

In [57]: s.str.match('m|h')
Out[57]: 
0     True
1     True
2    False
dtype: bool
In [58]: s.str[::-1].str.match('ta[f|g]|n') # 反转后匹配
Out[58]: 
0    False
1     True
2     True
dtype: bool

当然,这些也能通过在 str.contains 的正则中使用 ^$ 来实现:

In [59]: s.str.contains('^[m|h]')
Out[59]: 
0     True
1     True
2    False
dtype: bool
In [60]: s.str.contains('[f|g]at|n$')
Out[60]: 
0    False
1     True
2     True
dtype: bool

除了上述返回值为布尔的匹配之外,还有一种返回索引的匹配函数,即 str.findstr.rfind ,其分别返回从左到右和从右到左第一次匹配的位置的索引,未找到则返回-1。需要注意的是这两个函数不支持正则匹配,只能用于字符子串的匹配:

In [61]: s = pd.Series(['This is an apple. That is not an apple.'])
In [62]: s.str.find('apple')
Out[62]: 
0    11
dtype: int64
In [63]: s.str.rfind('apple')
Out[63]: 
0    33
dtype: int64

4. 替换

str.replacereplace 并不是一个函数,在使用字符串替换时应当使用前者。

In [64]: s = pd.Series(['a_1_b','c_?'])
In [65]: s.str.replace('\d|\?', 'new', regex=True)
Out[65]: 
0    a_new_b
1      c_new
dtype: object

当需要对不同部分进行有差别的替换时,可以利用 子组 的方法,并且此时可以通过传入自定义的替换函数来分别进行处理,注意 group(k) 代表匹配到的第 k 个子组(圆括号之间的内容):

In [66]: s = pd.Series(['上海市黄浦区方浜中路249号',
   ....:                '上海市宝山区密山路5号',
   ....:                '北京市昌平区北农路2号'])
   ....: 
In [67]: pat = '(\w+市)(\w+区)(\w+路)(\d+号)'
In [68]: city = {'上海市': 'Shanghai', '北京市': 'Beijing'}
In [69]: district = {'昌平区': 'CP District',
   ....:             '黄浦区': 'HP District',
   ....:             '宝山区': 'BS District'}
   ....: 
In [70]: road = {'方浜中路': 'Mid Fangbin Road',
   ....:         '密山路': 'Mishan Road',
   ....:         '北农路': 'Beinong Road'}
   ....: 
In [71]: def my_func(m):
   ....:     str_city = city[m.group(1)]
   ....:     str_district = district[m.group(2)]
   ....:     str_road = road[m.group(3)]
   ....:     str_no = 'No. ' + m.group(4)[:-1]
   ....:     return ' '.join([str_city,
   ....:                     str_district,
   ....:                     str_road,
   ....:                     str_no])
   ....: 
In [72]: s.str.replace(pat, my_func, regex=True)
Out[72]: 
0    Shanghai HP District Mid Fangbin Road No. 249
1           Shanghai BS District Mishan Road No. 5
2           Beijing CP District Beinong Road No. 2
dtype: object

这里的数字标识并不直观,可以使用 命名子组 更加清晰地写出子组代表的含义:

In [73]: pat = '(?P<市名>\w+市)(?P<区名>\w+区)(?P<路名>\w+路)(?P<编号>\d+号)'
In [74]: def my_func(m):
   ....:     str_city = city[m.group('市名')]
   ....:     str_district = district[m.group('区名')]
   ....:     str_road = road[m.group('路名')]
   ....:     str_no = 'No. ' + m.group('编号')[:-1]
   ....:     return ' '.join([str_city,
   ....:                     str_district,
   ....:                     str_road,
   ....:                     str_no])
   ....: 
In [75]: s.str.replace(pat, my_func, regex=True)
Out[75]: 
0    Shanghai HP District Mid Fangbin Road No. 249
1           Shanghai BS District Mishan Road No. 5
2           Beijing CP District Beinong Road No. 2
dtype: object

这里虽然看起来有些繁杂,但是实际数据处理中对应的替换,一般都会通过代码来获取数据从而构造字典映射,在具体写法上会简洁的多。

5. 提取

提取既可以认为是一种返回具体元素(而不是布尔值或元素对应的索引位置)的匹配操作,也可以认为是一种特殊的拆分操作。前面提到的 str.split 例子中会把分隔符去除,这并不是用户想要的效果,这时候就可以用 str.extract 进行提取:

In [76]: pat = '(\w+市)(\w+区)(\w+路)(\d+号)'
In [77]: s.str.extract(pat)
Out[77]: 
     0    1     2     3
0  上海市  黄浦区  方浜中路  249号
1  上海市  宝山区   密山路    5号
2  北京市  昌平区   北农路    2号

通过子组的命名,可以直接对新生成 DataFrame 的列命名:

In [78]: pat = '(?P<市名>\w+市)(?P<区名>\w+区)(?P<路名>\w+路)(?P<编号>\d+号)'
In [79]: s.str.extract(pat)
Out[79]: 
    市名   区名    路名    编号
0  上海市  黄浦区  方浜中路  249号
1  上海市  宝山区   密山路    5号
2  北京市  昌平区   北农路    2号

str.extractall 不同于 str.extract 只匹配一次,它会把所有符合条件的模式全部匹配出来,如果存在多个结果,则以多级索引的方式存储:

In [80]: s = pd.Series(['A135T15,A26S5','B674S2,B25T6'], index = ['my_A','my_B'])
In [81]: pat = '[A|B](\d+)[T|S](\d+)'
In [82]: s.str.extractall(pat)
Out[82]: 
              0   1
     match   
my_A 0      135  15
     1       26   5
my_B 0      674   2
     1       25   6
In [83]: pat_with_name = '[A|B](?P<name1>\d+)[T|S](?P<name2>\d+)'
In [84]: s.str.extractall(pat_with_name)
Out[84]: 
           name1 name2
     match    
my_A 0       135    15
     1        26     5
my_B 0       674     2
     1        25     6

str.findall 的功能类似于 str.extractall ,区别在于前者把结果存入列表中,而后者处理为多级索引,每个行只对应一组匹配,而不是把所有匹配组合构成列表。

In [85]: s.str.findall(pat)
Out[85]: 
my_A    [(135, 15), (26, 5)]
my_B     [(674, 2), (25, 6)]
dtype: object