目录
1. string类型的性质
1.1. string与object的区别
string类型和object有三处不同:
- 字符存取方法(string accessor methods,如str.count)会返回相应数据的Nullable类型,而object会随缺失值的存在而改变返回类型
- 某些Series方法不能在string上使用,例如: Series.str.decode(),因为存储的是字符串而不是字节
- string类型在缺失值存储或运算时,类型会广播为pd.NA,而不是浮点型np.nan
其余全部内容在当前版本下完全一致,但迎合Pandas的发展模式,我们仍然全部用string来操作字符串
2. string类型的转换
如果将一个其他类型的容器直接转换string类型可能会出错:
这个问题是python中类型转化是写str而不是string
#pd.Series([1,'1.']).astype('string') #报错
#pd.Series([1,2]).astype('string') #报错
#pd.Series([True,False]).astype('string') #报错
正确的方法如下:
pd.Series([1,'1.']).astype('str')
```python
0 1
1 1.
dtype: object
pd.Series([1,2]).astype('str')
0 1
1 2
dtype: object
pd.Series([True,False]).astype('str')
0 True
1 False
dtype: object
2.拆分与拼接
2.1. str.split方法
(a)分割符与str的位置元素选取
s = pd.Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'], dtype="str")
s
0 a_b_c
1 c_d_e
2 NaN
3 f_g_h
dtype: object
根据某一个元素分割,默认为空格
s.str.split('_')
0 [a, b, c]
1 [c, d, e]
2 NaN
3 [f, g, h]
dtype: object
对于str方法可以进行元素的选择,如果该单元格元素是列表,那么str[i]表示取出第i个元素,如果是单个元素,则先把元素转为列表在取出
s.str.split('_').str[1]
0 b
1 d
2 NaN
3 g
dtype: object
pd.Series(['a_b_c', ['a','b','c']], dtype="object").str[1]
#第一个元素先转为['a','_','b','_','c']
0 _
1 b
dtype: object
(b)其他参数
expand参数控制了是否将列拆开,n参数代表最多分割多少次
s.str.split('_',expand=True)
0 | 1 | 2 | |
---|---|---|---|
0 | a | b | c |
1 | c | d | e |
2 | NaN | NaN | NaN |
3 | f | g | h |
s.str.split('_',n=1)
0 [a, b_c]
1 [c, d_e]
2 NaN
3 [f, g_h]
dtype: object
s.str.split('_',expand=True,n=1)
0 | 1 | |
---|---|---|
0 | a | b_c |
1 | c | d_e |
2 | NaN | NaN |
3 | f | g_h |
2.2. str.cat方法
(a)不同对象的拼接模式
cat方法对于不同对象的作用结果并不相同,其中的对象包括:单列、双列、多列
- 对于单个Series而言,就是指所有的元素进行字符合并为一个字符串
s = pd.Series(['ab',None,'d'],dtype='str')
s
0 ab
1 None
2 d
dtype: object
s.str.cat()
'abd'
其中可选sep分隔符参数,和缺失值替代字符na_rep参数
s.str.cat(sep=',')
'ab,d'
s.str.cat(sep=',',na_rep='*')
'ab,*,d'
- 对于两个Series合并而言,是对应索引的元素进行合并
s2 = pd.Series(['24',None,None],dtype='string')
s2
0 24
1 None
2 None
dtype: object
s.str.cat(s2)
0 ab24
1 NaN
2 NaN
dtype: object
同样也有相应参数,需要注意的是两个缺失值会被同时替换
s.str.cat(s2,sep=',',na_rep='*')
0 ab,24
1 *,*
2 d,*
dtype: object
- 多列拼接可以分为表的拼接和多Series拼接
表的拼接
s.str.cat(pd.DataFrame({0:['1','3','5'],1:['5','b',None]},dtype='str'),na_rep='*')
0 ab15
1 *3b
2 d5*
dtype: object
多个Series拼接
s.str.cat([s+'0',s*2])
0 abab0abab
1 NaN
2 dd0dd
dtype: object
(b)cat中的索引对齐
当前版本中,如果两边合并的索引不相同且未指定join参数,默认为左连接,设置join=‘left’
s2 = pd.Series(list('abc'),index=[1,2,3],dtype='str')
s2
1 a
2 b
3 c
dtype: object
s.str.cat(s2,na_rep='*')
0 aba
1 *b
2 dc
dtype: object
3.替换
广义上的替换,就是指str.replace函数的应用,fillna是针对缺失值的替换,在之前的缺失值一文中已经提及
提到替换,就不可避免地接触到正则表达式
3.1. str.replace的常见用法
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca','', np.nan, 'CABA', 'dog', 'cat'],dtype="str")
s
0 A
1 B
2 C
3 Aaba
4 Baca
5
6 NaN
7 CABA
8 dog
9 cat
dtype: object
第一个值写r开头的正则表达式,后一个写替换的字符串
s.str.replace(r'^[AB]','***')
0 ***
1 ***
2 C
3 ***aba
4 ***aca
5
6 NaN
7 CABA
8 dog
9 cat
dtype: object
3.2. 子组与函数替换
通过正整数调用子组(0返回字符本身,从1开始才是子组)
s.str.replace(r'([ABC])(\w+)',lambda x:x.group(2)[1:]+'*')
0 A
1 B
2 C
3 ba*
4 ca*
5
6 NaN
7 BA*
8 dog
9 cat
dtype: object
利用?P<…>表达式可以对子组命名调用
s.str.replace(r'(?P<one>[ABC])(?P<two>\w+)',lambda x:x.group('two')[1:]+'*')
0 A
1 B
2 C
3 ba*
4 ca*
5
6 NaN
7 BA*
8 dog
9 cat
dtype: object
4.子串匹配与提取
4.1. str.extract方法
(a)常见用法
pd.Series(['10-87', '10-88', '10-89'],dtype="str").str.extract(r'([\d]{2})-([\d]{2})')
0 | 1 | |
---|---|---|
0 | 10 | 87 |
1 | 10 | 88 |
2 | 10 | 89 |
使用子组名作为列名
pd.Series(['10-87', '10-88', '-89'],dtype="str").str.extract(r'(?P<name_1>[\d]{2})-(?P<name_2>[\d]{2})')
name_1 | name_2 | |
---|---|---|
0 | 10 | 87 |
1 | 10 | 88 |
2 | NaN | NaN |
利用?正则标记选择部分提取
pd.Series(['10-87', '10-88', '-89'],dtype="str").str.extract(r'(?P<name_1>[\d]{2})?-(?P<name_2>[\d]{2})')
name_1 | name_2 | |
---|---|---|
0 | 10 | 87 |
1 | 10 | 88 |
2 | NaN | 89 |
pd.Series(['10-87', '10-88', '10-'],dtype="str").str.extract(r'(?P<name_1>[\d]{2})-(?P<name_2>[\d]{2})?')
name_1 | name_2 | |
---|---|---|
0 | 10 | 87 |
1 | 10 | 88 |
2 | 10 | NaN |
(b)expand参数(默认为True)
对于一个子组的Series,如果expand设置为False,则返回Series,若大于一个子组,则expand参数无效,全部返回DataFrame
对于一个子组的Index,如果expand设置为False,则返回提取后的Index,若大于一个子组且expand为False,报错
s = pd.Series(["a1", "b2", "c3"], ["A11", "B22", "C33"], dtype="str")
s.index
Index(['A11', 'B22', 'C33'], dtype='object')
s.str.extract(r'([\w])')
0 | |
---|---|
A11 | a |
B22 | b |
C33 | c |
s.str.extract(r'([\w])',expand=False)
A11 a
B22 b
C33 c
dtype: object
s.index.str.extract(r'([\w])')
0 | |
---|---|
0 | A |
1 | B |
2 | C |
s.index.str.extract(r'([\w])',expand=False)
Index(['A', 'B', 'C'], dtype='object')
s.index.str.extract(r'([\w])([\d])')
0 | 1 | |
---|---|---|
0 | A | 1 |
1 | B | 2 |
2 | C | 3 |
4.2. str.extractall方法
与extract只匹配第一个符合条件的表达式不同,extractall会找出所有符合条件的字符串,并建立多级索引
s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"],dtype="str")
two_groups = '(?P<letter>[a-z])(?P<digit>[0-9])'
s.str.extract(two_groups, expand=True)
letter | digit | |
---|---|---|
A | a | 1 |
B | b | 1 |
C | c | 1 |
s.str.extractall(two_groups)
letter | digit | ||
---|---|---|---|
match | |||
A | 0 | a | 1 |
1 | a | 2 | |
B | 0 | b | 1 |
C | 0 | c | 1 |
s['A']='a1'
s.str.extractall(two_groups)
letter | digit | ||
---|---|---|---|
match | |||
A | 0 | a | 1 |
B | 0 | b | 1 |
C | 0 | c | 1 |
如果想查看第i层匹配,可使用xs方法
s = pd.Series(["a1a2", "b1b2", "c1c2"], index=["A", "B", "C"],dtype="str")
s.str.extractall(two_groups).xs(1,level='match')
letter | digit | |
---|---|---|
A | a | 2 |
B | b | 2 |
C | c | 2 |
4.3. str.contains和str.match
前者的作用为检测是否包含某种正则模式
pd.Series(['1', None, '3a', '3b', '03c'], dtype="str").str.contains(r'[0-9][a-z]')
0 False
1 None
2 True
3 True
4 True
dtype: object
可选参数为na
pd.Series(['1', None, '3a', '3b', '03c'], dtype="str").str.contains('a', na=False)
0 False
1 False
2 True
3 False
4 False
dtype: bool
str.match与其区别在于,match依赖于python的re.match,检测内容为是否从头开始包含该正则模式
pd.Series(['1', None, '3a_', '3b', '03c'], dtype="str").str.match(r'[0-9][a-z]',na=False)
0 False
1 False
2 True
3 True
4 False
dtype: bool
pd.Series(['1', None, '_3a', '3b', '03c'], dtype="str").str.match(r'[0-9][a-z]',na=False)
0 False
1 False
2 False
3 True
4 False
dtype: bool
5.常用字符串方法
5.1. 过滤型方法
- str.strip
常用于过滤空格
pd.Series(list('abc'),index=[' space1 ','space2 ',' space3'],dtype="str").index.str.strip()
Index(['space1', 'space2', 'space3'], dtype='object')
- str.lower和str.upper
pd.Series('A',dtype="str").str.lower()
0 a
dtype: object
pd.Series('a',dtype="str").str.upper()
0 A
dtype: object
- str.swapcase和str.capitalize
分别表示交换字母大小写和大写首字母
pd.Series('abCD',dtype="str").str.swapcase()
0 ABcd
dtype: object
pd.Series('abCD',dtype="str").str.capitalize()
0 Abcd
dtype: object
5.2 isnumeric方法
检查每一位是否都是数字,请问如何判断是否是数值?
pd.Series(['1.2','1','-0.3','a',np.nan],dtype="str").str.isnumeric()
0 False
1 True
2 False
3 False
4 NaN
dtype: object