Datawhale组队-Pandas(下)文本数据(打卡)

一、string类型的性质

1.string和object的区别

string类型和object不同之处有三:

  • 字符存取方法(string accessor methods,如str.count)会返回相应数据的Nullable类型,而object会随缺失值的存在而改变返回类型
  • 某些Series方法不能在string上使用,例如:Series.str.decode(),因为存储的字符串而不是字节
  • string类型在缺失值存储或运算时,类型会广播为pd.NA,而不是浮点型np.nan

2.string类型的转换

如果将一个其他类型的容器直接转换string类型可能会出错,需要分成两个转换,先转成str型的object,然后再转成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').astype('string')
pd.Series([1,2]).astype('str').astype('string')
pd.Series([True,False]).astype('str').astype('string')

3. str和string的区别

(a)str字符串有三种写法:

单引号(Single quotes)、双引号(Double quotes)、三引号(Triple quoted)。

单双引号可以互相嵌套,三引号可以嵌套单双引号,使得字符串扩展为多行。若要嵌套自身,需要用反斜杠转移。

注:两个字符串字面量之间只有空格时,它们会被自动转换为一个字符串

二、拆分与拼接

1.str.split方法

(a)分割符与str的位置元素选取

s = pd.Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'], dtype="string")
s.str.split('_')

注意split后的类型是object,因为现在Series中的元素已经不是string,而包含了list,且string类型只能含有字符串

对于str方法可以进行元素的选择,如果该单元格元素是列表,那么str[i]表示取出第i个元素,如果是单个元素,则先把元素转为列表在取出

s.str.split('_').str[1]

(b)其他参数

expand参数控制了是否将列拆开,n参数代表最多分割多少次

2.str.cat方法

(a)不同对象的拼接模式

对于单个Series而言,指将所有的元素进行字符合并为字符串,其中可选sep分割符参数,和缺失值替代字符na_rep参数

s = pd.Series(['ab',None,'d'],dtype='string')
print(s)
s.str.cat(sep=',',na_rep='*')

对于两个Series合并而言,是对应索引的元素进行合并,同样也有相应参数,但是注意是两个缺失值被同时替换

​
s = pd.Series(['ab',None,'d'],dtype='string')
print(s)
s2 = pd.Series(['24',None,None],dtype='string')
print(s2)


#使用分割符​
s.str.cat(s2,sep=',',na_rep='*')

多列拼接可以分为表的拼接和多Series拼接

#表的拼接
s.str.cat(pd.DataFrame({0:['1','3','5'],1:['5','b',None]},dtype='string'),na_rep='*')


#多个Series拼接
s.str.cat([s+'0',s*2])

(b)cat中的索引对齐

当前版本中,如果两边合并的索引不相同且未指定join参数,默认为左连接,设置join='left'

s2 = pd.Series(list('abc'),index=[1,2,3],dtype='string')
print(s2)
s.str.cat(s2,na_rep='*')

三、替换

1.str.replace的常见用法

第一个值写r开头的正则表达式,后一个写替换的字符串

s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca','', np.nan, 'CABA', 'dog', 'cat'],dtype="string")
print(s)
s.str.replace(r'^[AB]','***')

2.子组与函数替换

通过正整数调用子组(0返回字符本身,从1开始才是子组)

s.str.replace(r'([ABC])(\w+)',lambda x:x.group(2)[1:]+'*')

利用?<...>表达书可以对子组命名调用

s.str.replace(r'(?P<one>[ABC])(?P<two>\w+)',lambda x:x.group('two')[1:]+'*')

3.str.replace注意事项

  • str.replace针对的是object类型或string类型,默认是以正则表达式为操作,目前暂时不支持DataFrame上使用
  • replace针对的是任意类型的序列或数据框,如果要以正则表达式替换,需要设置regex=True,该方法通过字典可支持多列替换,但现在由于string类型的初步引入,用法上出现了一些问题,这些issue有望在以后的版本中修复

(a)str.replace赋值参数不得为pd.NA

#pd.Series(['A','B'],dtype='string').str.replace(r'[A]',pd.NA) #报错
#pd.Series(['A','B'],dtype='O').str.replace(r'[A]',pd.NA) #报错

pd.Series(['A','B'],dtype='string').astype('O').replace(r'[A]',pd.NA,regex=True).astype('string')

(b)对于string类型Series,在使用replace函数时不能使用正则表达式替换

pd.Series(['A','B'],dtype='string').replace(r'[A]','C',regex=True)

pd.Series(['A','B'],dtype='O').replace(r'[A]','C',regex=True)

(c)string类型序列如果存在缺失值,不能使用replace替换

pd.Series(['A',np.nan],dtype='string').str.replace('A','B')

四、子串匹配与提取

1.str.extract方法

(a)常用方法

pd.Series(['10-87', '10-88', '10-89'],dtype="string").str.extract(r'([\d]{2})-([\d]{2})')

使用子组名作为列名

pd.Series(['10-87', '10-88', '-89'],dtype="string").str.extract(r'(?P<name_1>[\d]{2})-(?P<name_2>[\d]{2})')

利用?正则表计选择部分提取

pd.Series(['10-87', '10-88', '-89'],dtype="string").str.extract(r'(?P<name_1>[\d]{2})?-(?P<name_2>[\d]{2})')

(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="string")
s.index

s.str.extract(r'([\w])')

s.str.extract(r'([\w])',expand=False)

s.index.str.extract(r'([\w])')

s.index.str.extract(r'([\w])',expand=False)

s.index.str.extract(r'([\w])([\d])')

2.str.extractall方法

与extract只匹配第一个符合条件的表达式不同,extractall会找出所有符合条件的字符串,并建立多级索引(即使只找到一个)

s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"],dtype="string")
two_groups = '(?P<letter>[a-z])(?P<digit>[0-9])'
s.str.extract(two_groups, expand=True)

s.str.extractall(two_groups)

s['A']='a1'
s.str.extractall(two_groups)

s = pd.Series(["a1a2", "b1b2", "c1c2"], index=["A", "B", "C"],dtype="string")
s.str.extractall(two_groups).xs(1,level='match')

3.str.contains 和str.match

str.contains是检测是否包含某种正则模式,可选参数为na

#查看是否包含字母和数字
pd.Series(['1', None, '3a', '3b', '03c'], dtype="string").str.contains(r'[0-9][a-z]')
#查看是否包含a
pd.Series(['1', None, '3a', '3b', '03c'], dtype="string").str.contains('a', na=False)

str.match与str.contrains的区别在于,match依赖于python的re.match,检测内容是否从头开始包含该正则模式

pd.Series(['1', None, '3a_', '3b', '03c'], dtype="string").str.match(r'[0-9][a-z]',na=False)
pd.Series(['1', None, '_3a', '3b', '03c'], dtype="string").str.match(r'[0-9][a-z]',na=False)

五、常用字符串方法

1.过滤型方法

(a)str.strip 常同于过滤空格

pd.Series(list('abc'),index=[' space1  ','space2  ','  space3'],dtype="string").index.str.strip()

(b)str.lower(字母小写)和str.upper(字母大写)

pd.Series('A',dtype="string").str.lower()
pd.Series('a',dtype="string").str.upper()

(c)str.swapcase和str.capitalize(交换字母大小写和大写首字母)

pd.Series('abCD',dtype="string").str.swapcase()#大写变小写,小写变大写
pd.Series('abCD',dtype="string").str.capitalize()#将字符串的第一个字母变成大写,其他字母变小写

2.isnumeric方法

检查每一位是否都是数字,请问如何判断是否是数值

pd.Series(['1.2','1','-0.3','a',np.nan],dtype="string").str.isnumeric()

练习:

题二:

求col2的均值,要考虑怎么将字符串类型的负数转换为我们理解的负数,这里用split按照-分割,可将字符串分成两部分,整数则直接转换,负数则可以乘以-1进行转换,在转换过程遇到了0-,9‘,/7等不符合常规字符,可先将转换(前提是数量不多的情况下)。代码如下:

df.loc[[309,396,485],'col2'] = ['0','9','7']
collist = []
for i in range (df['col2'].shape[0]):
    strlist = df['col2'][i].split('-')
    if len(strlist)==2 and strlist[0] =='':
        col = int(strlist[1])*(-1)
    else:
        col = int(strlist[0])
    collist.append(col)
df['new_col2'] = collist
df['new_col2'].mean()

官方答案,正常思路是可以用正则表达式筛选出非常规字符,然后进行转换,正则表达式不太会,还在学习中:

df['col2'][~(df['col2'].str.replace(r'-?\d+','True')=='True')] #这三行有问题
df.loc[[309,396,485],'col2'] = [0,9,7]
df['col2'].astype('int').mean()

猜你喜欢

转载自blog.csdn.net/qq_28409193/article/details/106944210