pandas学习笔记(八)
一、str对象
1.str对象的设计意图
str对象:定义在Index或Series上的属性,专门用于逐元素处理文本内容,其内部定义了大量方法,因此对一个序列进行文本处理,首先需要获取其 str 对象。
在Python标准库中也有 str 模块,为了使用上的便利,有许多函数的用法 pandas 照搬了它的设计,例如字母转为大写的操作:
var = 'abcd'
str.upper(var) # Python内置str模块
Out[4]: 'ABCD'
s = pd.Series(['abcd','efg','hi'])
s
Out[6]:
0 abcd
1 efg
2 hi
dtype: object
s.str
Out[7]: <pandas.core.strings.StringMethods at 0x248f995acd0>
s.str.upper() # pandas中str对象上的upper方法
Out[8]:
0 ABCD
1 EFG
2 HI
dtype: object
2.[]索引器
对于 str 对象而言,可理解为其对字符串进行了序列化的操作,例如在一般的字符串中,通过 [] 可以取出某个位置的元素:
var[0]
Out[9]: 'a'
同时也能通过切片得到子串:
var[-1:0:-2]
Out[10]: 'db'
通过对 str 对象使用 [] 索引器,可以完成完全一致的功能,并且如果超出范围则返回缺失值:
s.str[0]
Out[12]:
0 a
1 e
2 h
dtype: object
s.str[-1:0:-2]
Out[13]:
0 db
1 g
2 i
dtype: object
s.str[2]
Out[14]:
0 c
1 g
2 NaN
dtype: object
3.string类型
引入string类型的动机:字符串有必要同数值型或 category 一样,具有自己的数据存放类型
绝大多数对于 object 和 string 类型的序列使用 str 对象方法产生的结果是一致,但是在下面提到的两点上有较大差异:
-
应当尽量保证每一个序列中的值都是字符串的情况下才使用 str 属性,但这并不是必须的,其必要条件是序列中至少有一个可迭代(Iterable)对象,包括但不限于字符串、字典、列表。对于一个可迭代对象, string 类型的 str 对象和 object 类型的 str 对象返回结果可能是不同的。
s = pd.Series([{1:'temp_1',2:'temp_2'},['a','b'],0.5,'my_string']) s Out[16]: 0 {1: 'temp_1', 2: 'temp_2'} 1 [a, b] 2 0.5 3 my_string dtype: object s.str[1] Out[17]: 0 temp_1 1 b 2 NaN 3 y dtype: object
-
对于某些对象的 str 序列化方法不同之外,两者另外的一个差别在于, string 类型是 Nullable 类型,但 object 不是。这意味着 string 类型的序列,如果调用的 str 方法返回值为整数 Series 和布尔 Series 时,其分别对应的 dtype 是 Int 和 boolean 的 Nullable 类型,而 object 类型则会分别返回 int/float 和 bool/object ,取决于缺失值的存在与否。同时,字符串的比较操作,也具有相似的特性, string 返回 Nullable 类型,但 object 不会。
s = pd.Series(['a']) s Out[22]: 0 a dtype: object s.str.len() Out[23]: 0 1 dtype: int64 s.astype('string').str.len() Out[24]: 0 1 dtype: Int64 s == 'a' Out[25]: 0 True dtype: bool s.astype('string') == 'a' Out[26]: 0 True dtype: boolean s = pd.Series(['a',np.nan]) # 带有缺失值 s.str.len() Out[28]: 0 1.0 1 NaN dtype: float64 s.astype('string').str.len() Out[30]: 0 1 1 <NA> dtype: s == 'a' Out[31]: 0 True 1 False dtype: bool s.astype('string') == 'a' Out[32]: 0 True 1 <NA> dtype: boolean
-
对于全体元素为数值类型的序列,即使其类型为 object 或者 category 也不允许直接使用 str 属性。如果需要把数字当成 string 类型处理,可以使用 astype 强制转换为 string 类型的 Series :
s = pd.Series([12,345,6789]) s.astype('string').str[0] Out[36]: 0 1 1 3 2 6 dtype: string
二、正则表达式基础
1.一般字符的匹配
正则表达式是一种按照某种正则模式,从左到右匹配字符串中内容的一种工具。
使用了 python 中 re 模块的 findall 函数来匹配所有出现过但不重叠的模式,第一个参数是正则表达式,第二个参数是待匹配的字符串。
例如,在下面的字符串中找出 apple :
import re
re.findall(r'Apple','Apple! This Is an Apple!')
Out[38]: ['Apple', 'Apple']
2.元字符基础
元字符 | 描述 |
---|---|
. | 匹配除换行符以外的任意字符 |
[ ] | 字符类,匹配方括号中包含的任意字符。 |
[^ ] | 否定字符类,匹配方括号中不包含的任意字符 |
* | 匹配前面的子表达式零次或多次 |
+ | 匹配前面的子表达式一次或多次 |
? | 匹配前面的子表达式零次或一次 |
{n,m} | 花括号,匹配前面字符至少 n 次,但是不超过 m 次 |
(xyz) | 字符组,按照确切的顺序匹配字符xyz。 |
| | 分支结构,匹配符号之前的字符或后面的字符 |
\ | 转义符,它可以还原元字符原来的含义 |
^ | 匹配行的开始 |
$ | 匹配行的结束 |
re.findall(r'.','abc')
Out[42]: ['a', 'b', 'c']
re.findall(r'[ac]','abc')
Out[43]: ['a', 'c']
re.findall(r'[^ac]','abc')
Out[44]: ['b']
re.findall(r'[ac]{2}','aaaaaaacccccc') #{n}指匹配n次
Out[46]: ['aa', 'aa', 'aa', 'ac', 'cc', 'cc']
re.findall(r'aaa|bbb','aaaaabbbb')
Out[51]: ['aaa', 'bbb']
re.findall(r'aaa|bbb','aaaaabb')
Out[52]: ['aaa']
re.findall(r'a\\?|a\*','aa?a*a')
Out[53]: ['a', 'a', 'a', 'a']
3.简写字符集
此外,正则表达式中还有一类简写字符集,其等价于一组字符的集合:
简写 | 描述 |
---|---|
\w | 匹配所有字母、数字、下划线: [a-zA-Z0-9_] |
\W | 匹配非字母和数字的字符: [^\w] |
\d | 匹配数字: [0-9] |
\D | 匹配非数字: [^\d] |
\s | 匹配空格符: [\t\n\f\r\p{Z}] |
\S | 匹配非空格符: [^\s] |
\B | 匹配一组非空字符开头或结尾的位置,不代表具体字符 |
re.findall(r'.s', 'Apple! This Is an Apple!')
Out[37]: ['is', 'Is']
re.findall(r'\w{2}', '09 8? 7w c_ 9q p@')
Out[38]: ['09', '7w', 'c_', '9q']
re.findall(r'\w\W\B', '09 8? 7w c_ 9q p@')
Out[39]: ['8?', 'p@']
re.findall(r'.\s.', 'Constant dropping wears the stone.')
Out[40]: ['t d', 'g w', 's t', 'e s']
re.findall(r'上海市(.{2,3}区)(.{2,3}路)(\d+号)',
'上海市黄浦区方浜中路249号 上海市宝山区密山路5号')
Out[41]: [('黄浦区', '方浜中路', '249号'), ('宝山区', '密山路', '5号')]
三、文本处理的五类操作
1.拆分
-
str.split 能够把字符串的列进行拆分,其中第一个参数为正则表达式,可选参数包括从左到右的最大拆分次数 n ,是否展开为多个列 expand 。
s = pd.Series(['上海市黄浦区方浜中路249号', ...: '上海市宝山区密山路5号']) s Out[55]: 0 上海市黄浦区方浜中路249号 1 上海市宝山区密山路5号 dtype: object s.str.split('[市区路]') Out[56]: 0 [上海, 黄浦, 方浜中, 249号] 1 [上海, 宝山, 密山, 5号] dtype: object s.str.split('[市区路]',n=2,expand=True) Out[57]: 0 1 2 0 上海 黄浦 方浜中路249号 1 上海 宝山 密山路5号
-
str.rsplit使用 n 参数的时候是从右到左限制最大拆分次数。但是当前版本下 rsplit 因为 bug 而无法使用正则表达式进行分割:
s.str.rsplit('[市区路]', n=2, expand=True) Out[58]: 0 0 上海市黄浦区方浜中路249号 1 上海市宝山区密山路5号
2.合并
-
str.join表示用某个连接符把 Series 中的字符串列表连接起来,如果列表中出现了非字符串元素则返回缺失值:
s = pd.Series([['a','b'],[1,'a'],[['a','b'],'c']]) s Out[60]: 0 [a, b] 1 [1, a] 2 [[a, b], c] dtype: object s.str.join('-') Out[61]: 0 a-b 1 NaN 2 NaN dtype: object
-
str.cat 用于合并两个序列,主要参数为连接符 sep 、连接形式 join 以及缺失值替代符号na_rep ,其中连接形式默认为以索引为键的左连接。
s1 = pd.Series(['a','b']) s2 = pd.Series(['cat','dog']) s1.str.cat(s2,sep='-') Out[65]: 0 a-cat 1 b-dog dtype: object s2.index = [1,2] s1.str.cat(s2,sep='-',na_rep='?',join='outer') Out[69]: 0 a-? 1 b-cat 2 ?-dog dtype: object
3.匹配
-
str.contains 返回了每个字符串是否包含正则模式的布尔序列:
s = pd.Series(['my cat','he is cat','railway station']) s Out[71]: 0 my cat 1 he is cat 2 railway station dtype: object s.str.contains('\s\wat') Out[72]: 0 True 1 True 2 False dtype: bool
-
str.startswith 和 str.endswith 返回了每个字符串以给定模式为开始和结束的布尔序列,它们都不支持正则表达式:
s.str.startswith('my') Out[73]: 0 True 1 False 2 False dtype: bool s.str.endswith('t') Out[74]: 0 True 1 True 2 False
-
str.match返回了每个字符串起始处是否符合给定正则模式的布尔序列:
s.str.match('m|h') Out[76]: 0 True 1 True 2 False dtype: bool s.str[::-1].str.match('ta[f|g]|n') # 反转后匹配 Out[77]: 0 False 1 False 2 True dtype: bool
-
str.find和str.rfind,其分别返回从左到右和从右到左第一次匹配的位置的索引,未找到则返回-1。需要注意的是这两个函数不支持正则匹配,只能用于字符子串的匹配:
s = pd.Series(['This is an apple. That is not an apple.']) s Out[83]: 0 This is an apple. That is not an apple. dtype: object s.str.find('applr') Out[84]: 0 -1 dtype: int64 s.str.find('apple') Out[85]: 0 11 dtype: int64 s.str.rfind('apple') Out[86]: 0 33 dtype: int64
4.替换
str.replace 和 replace 并不是一个函数,在使用字符串替换时应当使用前者。
s = pd.Series(['a_1_b','c_?'])
s
Out[88]:
0 a_1_b
1 c_?
dtype: object
s.str.replace('\d|\?','new',regex=True)
Out[89]:
0 a_new_b
1 c_new
dtype: object
当需要对不同部分进行有差别的替换时,可以利用 子组 的方法,并且此时可以通过传入自定义的替换函数来分别进行处理,注意 group(k) 代表匹配到的第 k 个子组(圆括号之间的内容):
s = pd.Series(['上海市黄浦区方浜中路249号',
...: '上海市宝山区密山路5号',
...: '北京市昌平区北农路2号'])
pat = '(\w+市)(\w+区)(\w+路)(\d+号)'
city = {'上海市': 'Shanghai', '北京市': 'Beijing'}
district = {'昌平区': 'CP District',
...: '黄浦区': 'HP District',
...: '宝山区': 'BS District'}
road = {'方浜中路': 'Mid Fangbin Road',
...: '密山路': 'Mishan Road',
...: '北农路': 'Beinong Road'}
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])
s.str.replace(pat,my_func,regex=True)
Out[97]:
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.extract进行提取
pat = '(\w+市)(\w+区)(\w+路)(\d+号)' s.str.extract(pat) Out[99]: 0 1 2 3 0 上海市 黄浦区 方浜中路 249号 1 上海市 宝山区 密山路 5号 2 北京市 昌平区 北农路 2号
通过子组的命名,可以直接对新生成 DataFrame 的列命名:
pat = '(?P<市名>\w+市)(?P<区名>\w+区)(?P<路名>\w+路)(?P<编号>\d+号)' s.str.extract(pat) Out[101]: 市名 区名 路名 编号 0 上海市 黄浦区 方浜中路 249号 1 上海市 宝山区 密山路 5号 2 北京市 昌平区 北农路 2号
-
str.extractall 不同于 str.extract 只匹配一次,它会把所有符合条件的模式全部匹配出来,如果存在多个结果,则以多级索引的方式存储:
s = pd.Series(['A135T15,A26S5','B674S2,B25T6'], index = ['my_A','my_B']) s Out[103]: my_A A135T15,A26S5 my_B B674S2,B25T6 dtype: object pat = '[A|B](\d+)[T|S](\d+)' s.str.extractall(pat) Out[105]: 0 1 match my_A 0 135 15 1 26 5 my_B 0 674 2 1 25 6 pat_with_name = '[A|B](?P<name1>\d+)[T|S](?P<name2>\d+)' s.str.extractall(pat_with_name) Out[111]: name1 name2 match my_A 0 135 15 1 26 5 my_B 0 674 2 1 25 6
-
str.findall 的功能类似于 str.extractall ,区别在于前者把结果存入列表中,而后者处理为多级索引,每个行只对应一组匹配,而不是把所有匹配组合构成列表。
s.str.findall(pat) Out[112]: my_A [(135, 15), (26, 5)] my_B [(674, 2), (25, 6)] dtype: object