第7章 文本数据

第7章 文本数据

在这里插入图片描述

import pandas as pd
import numpy as np

一、string类型的性质

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类型可能会出错:
#pd.Series([1,'1.']).astype('string') #报错
#pd.Series([1,2]).astype('string') #报错
#pd.Series([True,False]).astype('string') #报错
当下正确的方法是分两部转换,先转为str型object,在转为string类型:
pd.Series([1,'1.']).astype('str').astype('string')
0     1
1    1.
dtype: string
pd.Series([1,2]).astype('str').astype('string')
0    1
1    2
dtype: string
pd.Series([True,False]).astype('str').astype('string')
0     True
1    False
dtype: string

二、拆分与拼接

1. str.split方法

(a)分割符与str的位置元素选取
s = pd.Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'], dtype="string")
s
0    a_b_c
1    c_d_e
2     <NA>
3    f_g_h
dtype: string
根据某一个元素分割,默认为空格
s.str.split('_')
0    [a, b, c]
1    [c, d, e]
2         <NA>
3    [f, g, h]
dtype: object
这里需要注意split后的类型是object,因为现在Series中的元素已经不是string,而包含了list,且string类型只能含有字符串
对于str方法可以进行元素的选择,如果该单元格元素是列表,那么str[i]表示取出第i个元素,如果是单个元素,则先把元素转为列表在取出
s.str.split('_').str[1]
0       b
1       d
2    <NA>
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)
012
0abc
1cde
2<NA><NA><NA>
3fgh
s.str.split('_',n=1)
0    [a, b_c]
1    [c, d_e]
2        <NA>
3    [f, g_h]
dtype: object
s.str.split('_',expand=True,n=1)
01
0ab_c
1cd_e
2<NA><NA>
3fg_h

2. str.cat方法

(a)不同对象的拼接模式
cat方法对于不同对象的作用结果并不相同,其中的对象包括:单列、双列、多列
① 对于单个Series而言,就是指所有的元素进行字符合并为一个字符串
s = pd.Series(['ab',None,'d'],dtype='string')
s
0      ab
1    <NA>
2       d
dtype: string
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    <NA>
2    <NA>
dtype: string
s.str.cat(s2)

0    ab24
1    <NA>
2    <NA>
dtype: string
同样也有相应参数,需要注意的是两个缺失值会被同时替换
s.str.cat(s2,sep=',',na_rep='*')
0    ab,24
1      *,*
2      d,*
dtype: string
③ 多列拼接可以分为表的拼接和多Series拼接
表的拼接
s.str.cat(pd.DataFrame({0:['1','3','5'],1:['5','b',None]},dtype='string'),na_rep='*')
0    ab15
1     *3b
2     d5*
dtype: string
多个Series拼接
s.str.cat([s+'0',s*2])
0    abab0abab
1         <NA>
2        dd0dd
dtype: string
(b)cat中的索引对齐
当前版本中,如果两边合并的索引不相同且未指定join参数,默认为左连接,设置join=‘left’
s2 = pd.Series(list('abc'),index=[1,2,3],dtype='string')
s2
1    a
2    b
3    c
dtype: string
s.str.cat(s2,na_rep='*')
0    ab*
1     *a
2     db
dtype: string

三、替换

广义上的替换,就是指str.replace函数的应用,fillna是针对缺失值的替换,上一章已经提及
提到替换,就不可避免地接触到正则表达式,这里默认读者已掌握常见正则表达式知识点,若对其还不了解的,可以通过这份资料来熟悉

1. str.replace的常见用法

s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca','', np.nan, 'CABA', 'dog', 'cat'],dtype="string")
s
0       A
1       B
2       C
3    Aaba
4    Baca
5        
6    <NA>
7    CABA
8     dog
9     cat
dtype: string
第一个值写r开头的正则表达式,后一个写替换的字符串
s.str.replace(r'^[AB]','***')
0       ***
1       ***
2         C
3    ***aba
4    ***aca
5          
6      <NA>
7      CABA
8       dog
9       cat
dtype: string

2. 子组与函数替换

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

https://blog.csdn.net/yg_2012/article/details/75426842

  • group的意思是你的正则表达式是由好多组组成的,然后用字符串去匹配这个表达式,group(1)指的是匹配到了正则表达式第一组的子串是什么,group(2)是指匹配到了正则表达式第二组的子串是什么, groups()就是由所有子串组成的集合。

PS:下面看下正则表达式 \w \s \d \b

. 匹配除换行符以外的任意字符

\w 匹配字母或数字或下划线或汉字 等价于 ‘[^A-Za-z0-9_]’。

\s 匹配任意的空白符

\d 匹配数字

\b 匹配单词的开始或结束

^ 匹配字符串的开始

$ 匹配字符串的结束

\w能不能匹配汉字要视你的操作系统和你的应用环境而定

s.str.replace(r'([ABC])(\w+)',lambda x:x.group(2)[1:]+'*')
0       A
1       B
2       C
3     ba*
4     ca*
5        
6    <NA>
7     BA*
8     dog
9     cat
dtype: string
s.str.replace(r'([ABC])(\w+)',lambda x:print(x,'               ',x.group(2) ))#
<_sre.SRE_Match object; span=(0, 4), match='Aaba'>                 aba
<_sre.SRE_Match object; span=(0, 4), match='Baca'>                 aca
<_sre.SRE_Match object; span=(0, 4), match='CABA'>                 ABA





0       A
1       B
2       C
3        
4        
5        
6    <NA>
7        
8     dog
9     cat
dtype: string
利用?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    <NA>
7     BA*
8     dog
9     cat
dtype: string

3. 关于str.replace的注意事项

首先,要明确str.replace和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) #报错
此时,可以先转为object类型再转换回来,曲线救国:
pd.Series(['A','B'],dtype='string').astype('O').replace(r'[A]',pd.NA,regex=True).astype('string')
0    <NA>
1       B
dtype: string
至于为什么不用replace函数的regex替换(但string类型replace的非正则替换是可以的),原因在下面一条
(b)对于string类型Series,在使用replace函数时不能使用正则表达式替换
该bug现在还未修复
pd.Series(['A','B'],dtype='string').replace(r'[A]','C',regex=True)
0    A
1    B
dtype: string
pd.Series(['A','B'],dtype='O').replace(r'[A]','C',regex=True)
0    C
1    B
dtype: object
(c)string类型序列如果存在缺失值,不能使用replace替换
#pd.Series(['A',np.nan],dtype='string').replace('A','B') #报错
pd.Series(['A',np.nan],dtype='string').str.replace('A','B')
0       B
1    <NA>
dtype: string
综上,概况的说,除非需要赋值元素为缺失值(转为object再转回来),否则请使用str.replace方法

四、子串匹配与提取

1. str.extract方法

(a)常见用法
pd.Series(['10-87', '10-88', '10-89'],dtype="string").str.extract(r'([\d]{2})-([\d]{2})')
01
01087
11088
21089
使用子组名作为列名
pd.Series(['10-87', '10-88', '-89'],dtype="string").str.extract(r'(?P<name_1>[\d]{2})-(?P<name_2>[\d]{2})')
name_1name_2
01087
11088
2<NA><NA>
利用?正则标记选择部分提取
pd.Series(['10-87', '10-88', '-89'],dtype="string").str.extract(r'(?P<name_1>[\d]{2})?-(?P<name_2>[\d]{2})')
name_1name_2
01087
11088
2<NA>89
pd.Series(['10-87', '10-88', '10-'],dtype="string").str.extract(r'(?P<name_1>[\d]{2})-(?P<name_2>[\d]{2})?')
name_1name_2
01087
11088
210<NA>
(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
Index(['A11', 'B22', 'C33'], dtype='object')
s.str.extract(r'([\w])')
0
A11a
B22b
C33c
s.str.extract(r'([\w])',expand=False)
A11    a
B22    b
C33    c
dtype: string
s.index.str.extract(r'([\w])')
0
0A
1B
2C
s.index.str.extract(r'([\w])',expand=False)
Index(['A', 'B', 'C'], dtype='object')
s.index.str.extract(r'([\w])([\d])')
01
0A1
1B2
2C3
#s.index.str.extract(r'([\w])([\d])',expand=False) #报错

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)
letterdigit
Aa1
Bb1
Cc1
s.str.extractall(two_groups)
letterdigit
match
A0a1
1a2
B0b1
C0c1
s['A']='a1'
s.str.extractall(two_groups)
letterdigit
match
A0a1
B0b1
C0c1
如果想查看第i层匹配,可使用xs方法
s = pd.Series(["a1a2", "b1b2", "c1c2"], index=["A", "B", "C"],dtype="string")
s.str.extractall(two_groups).xs(1,level='match')
letterdigit
Aa2
Bb2
Cc2

3. str.contains和str.match

前者的作用为检测是否包含某种正则模式
pd.Series(['1', None, '3a', '3b', '03c'], dtype="string").str.contains(r'[0-9][a-z]')
0    False
1     <NA>
2     True
3     True
4     True
dtype: boolean
可选参数为na
pd.Series(['1', None, '3a', '3b', '03c'], dtype="string").str.contains('a', na=False)
0    False
1    False
2     True
3    False
4    False
dtype: boolean
str.match与其区别在于,match依赖于python的re.match,检测内容为是否从头开始包含该正则模式
pd.Series(['1', None, '3a_', '3b', '03c'], dtype="string").str.match(r'[0-9][a-z]',na=False)
0    False
1    False
2     True
3     True
4    False
dtype: boolean
pd.Series(['1', None, '_3a', '3b', '03c'], dtype="string").str.match(r'[0-9][a-z]',na=False)
0    False
1    False
2    False
3     True
4    False
dtype: boolean

五、常用字符串方法

1. 过滤型方法

(a)str.strip
常用于过滤空格
pd.Series(list('abc'),index=[' space1  ','space2  ','  space3'],dtype="string").index.str.strip()
Index(['space1', 'space2', 'space3'], dtype='object')
(b)str.lower和str.upper
pd.Series('A',dtype="string").str.lower()
0    a
dtype: string
pd.Series('a',dtype="string").str.upper()
0    A
dtype: string
(c)str.swapcase和str.capitalize
分别表示交换字母大小写和大写首字母
pd.Series('abCD',dtype="string").str.swapcase()
0    ABcd
dtype: string
pd.Series('abCD',dtype="string").str.capitalize()
0    Abcd
dtype: string

2. isnumeric方法

检查每一位是否都是数字,请问如何判断是否是数值?(问题二)
pd.Series(['1.2','1','-0.3','a',np.nan],dtype="string").str.isnumeric()

0    False
1     True
2    False
3    False
4     <NA>
dtype: boolean
pd.Series(['1.2','1','-0.3','a',np.nan,1]).apply(lambda x:True if type(x)in [float,int] and x==x else False)
# type(pd.Series(['1.2','1','-0.3','a',np.nan,1])[2])
# pd.Series(['1.2','1','-0.3','a',np.nan,1]).apply(lambda x:print(str(type(x))))
0    False
1    False
2    False
3    False
4    False
5     True
dtype: bool

六、问题与练习

1. 问题

【问题一】 str对象方法和df/Series对象方法有什么区别?

Pandas 为 Series 提供了 str 属性,通过它可以方便的对每个元素进行操作。

  • 在对 Series 中每个元素处理时,我们可以使用 map 或 apply 方法。
  • 比如,我想要将每个城市都转为小写,可以使用如下的方式。
  • user_info.city.map(lambda x: x.lower())#报错
  • 错误原因是因为 float 类型的对象没有 lower 属性。这是因为缺失值(np.nan)属于float 类型。
  • 这时候我们的 str 属性操作来了
  • user_info.city.str.lower()
  • 可以看到,通过 str 属性来访问之后用到的方法名与 Python 内置的字符串的方法名一样。并且能够自动排除缺失值。

from https://zhuanlan.zhihu.com/p/38603837

个人理解str对象方法更多的是对于Series中的每个小的元素进行处理的时候,把每个小元素当成字符串进行处理,并且方法名也跟python内置的字符串的方法名一样。

【问题二】 给出一列string类型,如何判断单元格是否是数值型数据?
pd.Series(['1.2','1','-0.3','a',np.nan,1]).apply(lambda x:True if type(x)in [float,int] and x==x else False)
0    False
1    False
2    False
3    False
4    False
5     True
dtype: bool
【问题三】 rsplit方法的作用是什么?它在什么场合下适用?

split()正序分割列;rsplit()逆序分割列

s=pd.Series(['   11    111  111 第一大类','    12 第一大类','    21 第二大类','    22 第二大类'])
s.str.rsplit(expand=True,n=1)
01
011 111 111第一大类
112第一大类
221第二大类
322第二大类

rsplit()是逆序分割,当我们最后面有几列需要单独分割出来,而且由于列数比较多从正着数不知道第几列或者是每一行列数都不一样而我们只需要最后一列,再这种情况下感觉是需要用到rsplit()的。

【问题四】 在本章的第二到第四节分别介绍了字符串类型的5类操作,请思考它们各自应用于什么场景?

拆分.str.split()

  • 可能应用于将单独的一列分成好几列,比如讲日期中的年份一列单独拿出来方便后面做分析

拼接.str.cat()

  • 将几列拼接起来生成新的一列,有的时候可能根据几列的信息整理出来一个新的重要的信息单独成一列

替换.str.replace()

  • 在每个元素中查找对应的元素,然后进行替换,可能在对于数据整体进行更新的时候可能会用到替换

匹配.str.contains() .str.match()

  • 查找每个元素中包不包含某种的特定的正则表达式

提取.str.extract() .str.extractall()

  • 查找每个元素中特定的正则表达式的格式的内容并提取出来

2. 练习

【练习一】 现有一份关于字符串的数据集,请解决以下问题:
(a)现对字符串编码存储人员信息(在编号后添加ID列),使用如下格式:“×××(名字):×国人,性别×,生于×年×月×日”
pd.read_csv('data/String_data_one.csv',index_col='人员编号').head()
姓名国籍性别出生年出生月出生日
人员编号
1aesfd21942810
2fasefa51985104
3aeagd419461015
4aef41999513
5eaf12010624
# a['国籍'].astype(str).astype('string')
a=pd.read_csv('data/String_data_one.csv',index_col='人员编号')#.convert_dtypes()
a['ID']=a['姓名']
a['ID']=a['ID'].str.cat(["(名字)"+':'+a['国籍'].astype(str).astype('string')+'国人,性别'+a['性别']+',生于'+a['出生年'].astype(str).astype('string')+'年'+a['出生月'].astype(str).astype('string')+'月'+a['出生日'].astype(str).astype('string')+'日'])
a.head()
姓名国籍性别出生年出生月出生日ID
人员编号
1aesfd21942810aesfd(名字):2国人,性别男,生于1942年8月10日
2fasefa51985104fasefa(名字):5国人,性别女,生于1985年10月4日
3aeagd419461015aeagd(名字):4国人,性别女,生于1946年10月15日
4aef41999513aef(名字):4国人,性别男,生于1999年5月13日
5eaf12010624eaf(名字):1国人,性别女,生于2010年6月24日
参考答案
df = pd.read_csv('data/String_data_one.csv',index_col='人员编号').astype('str')
(df['姓名']+':'+df['国籍']+'国人,性别'
          +df['性别']+',生于'
          +df['出生年']+'年'
          +df['出生月']+'月'+df['出生日']+'日').to_frame().rename(columns={0:'ID'}).head()
ID
人员编号
1aesfd:2国人,性别男,生于1942年8月10日
2fasefa:5国人,性别女,生于1985年10月4日
3aeagd:4国人,性别女,生于1946年10月15日
4aef:4国人,性别男,生于1999年5月13日
5eaf:1国人,性别女,生于2010年6月24日
(b)将(a)中的人员生日信息部分修改为用中文表示(如一九七四年十月二十三日),其余返回格式不变。
def f(s):
    map={'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九','10':'十','11':'十一','12':'十二'}
    re=''
    for i in s:
        re+=map[i]
    return re
def f2(s):
    map={'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九','10':'十','11':'十一','12':'十二'}
    return map[s]
def f3(s):
    map={'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九','10':'十','11':'十一','12':'十二'}
    if len(s)==1:
        return map[s]
    elif s[1]=='0':
        return map[s[0]]+'十'
    else:
        return map[s[0]]+'十'+map[s[1]]
a=pd.read_csv('data/String_data_one.csv',index_col='人员编号')#.convert_dtypes()
a['ID']=a['姓名']
a['ID']=a['ID'].str.cat([':'+a['国籍'].astype(str).astype('string')+'国人,性别'+a['性别']+',生于'+a['出生年'].astype(str).astype('string').apply(lambda x: f(x))+'年'+a['出生月'].astype(str).astype('string').apply(lambda x:f2(x))+'月'+a['出生日'].astype(str).astype('string').apply(lambda x:f3(x))+'日'])
a.head()#"(名字)"+
姓名国籍性别出生年出生月出生日ID
人员编号
1aesfd21942810aesfd:2国人,性别男,生于一九四二年八月一十日
2fasefa51985104fasefa:5国人,性别女,生于一九八五年十月四日
3aeagd419461015aeagd:4国人,性别女,生于一九四六年十月一十五日
4aef41999513aef:4国人,性别男,生于一九九九年五月一十三日
5eaf12010624eaf:1国人,性别女,生于二零一零年六月二十四日
# a['ID'].str.extract(r'(?P<姓名>[a-zA-Z]+):(?P<国籍>[\d])国人,性别(?P<性别>[\w]),生于(?P<出生年>[\w]{4})年(?P<出生月>[\w]+)月(?P<出生日>[\w]+)日')#,生于
参考答案
L_year = list('零一二三四五六七八九')
L_one = [s.strip() for s in list('  二三四五六七八九')]
L_two = [s.strip() for s in list(' 一二三四五六七八九')]
df_new = (df['姓名']+':'+df['国籍']+'国人,性别'+df['性别']+',生于'
          +df['出生年'].str.replace(r'\d',lambda x:L_year[int(x.group(0))])+'年'
          +df['出生月'].apply(lambda x:x if len(x)==2 else '0'+x)\
                      .str.replace(r'(?P<one>[\d])(?P<two>\d?)',lambda x:L_one[int(x.group('one'))]
                      +bool(int(x.group('one')))*'十'+L_two[int(x.group('two'))])+'月'
          +df['出生日'].apply(lambda x:x if len(x)==2 else '0'+x)\
                      .str.replace(r'(?P<one>[\d])(?P<two>\d?)',lambda x:L_one[int(x.group('one'))]
                      +bool(int(x.group('one')))*'十'+L_two[int(x.group('two'))])+'日')\
          .to_frame().rename(columns={0:'ID'})
df_new.head()
ID
人员编号
1aesfd:2国人,性别男,生于一九四二年八月十日
2fasefa:5国人,性别女,生于一九八五年十月四日
3aeagd:4国人,性别女,生于一九四六年十月十五日
4aef:4国人,性别男,生于一九九九年五月十三日
5eaf:1国人,性别女,生于二零一零年六月二十四日
(c)将(b)中的ID列结果拆分为原列表相应的5列,并使用equals检验是否一致。
re=a['ID'].str.extract(r'(?P<姓名>[a-zA-Z]{1,}):(?P<国籍>[\d])国人,性别(?P<性别>[\w]),生于(?P<出生年>[\w]{4})年(?P<出生月>[\w]+)月(?P<出生日>[\w]+)日')
def f11(s):
    map={'零':'0','一':'1','二':'2','三':'3','四':'4','五':'5','六':'6','七':'7','八':'8','九':'9','十':'10'}
    re=''
    for i in s:
        re+=map[i]
    return re
def f22(s):
    map={'零':'0','一':'1','二':'2','三':'3','四':'4','五':'5','六':'6','七':'7','八':'8','九':'9','十':'10','十一':'11','十二':'12'}
    return map[s]
def f33(s):
    re=''
    if len(s)>=2 and  s[-2]=='十':
        map={'零':'0','一':'1','二':'2','三':'3','四':'4','五':'5','六':'6','七':'7','八':'8','九':'9','十':''}
        for i in s:
            re+=map[i]
        return re
    elif s[-1]=='十':
        map={'零':'0','一':'1','二':'2','三':'3','四':'4','五':'5','六':'6','七':'7','八':'8','九':'9','十':'0'}
        for i in s:
            re+=map[i]
        return re
    else:
        map={'零':'0','一':'1','二':'2','三':'3','四':'4','五':'5','六':'6','七':'7','八':'8','九':'9','十':'10'}
        re=''
        for i in s:
            re+=map[i]
        return re

re['出生年']=re['出生年'].apply(lambda x:f11(x))
re['出生月']=re['出生月'].apply(lambda x:f22(x))
re['出生日']=re['出生日'].apply(lambda x:f33(x))
re.head()
            
    
    
姓名国籍性别出生年出生月出生日
人员编号
1aesfd21942810
2fasefa51985104
3aeagd419461015
4aef41999513
5eaf12010624
test=pd.read_csv('data/String_data_one.csv',index_col='人员编号').astype(str)#.convert_dtypes()
re.equals(test)
True
test.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2000 entries, 1 to 2000
Data columns (total 6 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   姓名      2000 non-null   object
 1   国籍      2000 non-null   object
 2   性别      2000 non-null   object
 3   出生年     2000 non-null   object
 4   出生月     2000 non-null   object
 5   出生日     2000 non-null   object
dtypes: object(6)
memory usage: 109.4+ KB
re.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2000 entries, 1 to 2000
Data columns (total 6 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   姓名      2000 non-null   object
 1   国籍      2000 non-null   object
 2   性别      2000 non-null   object
 3   出生年     2000 non-null   object
 4   出生月     2000 non-null   object
 5   出生日     2000 non-null   object
dtypes: object(6)
memory usage: 109.4+ KB
参考答案
dic_year = {i[0]:i[1] for i in zip(list('零一二三四五六七八九'),list('0123456789'))}
dic_two = {i[0]:i[1] for i in zip(list('十一二三四五六七八九'),list('0123456789'))}
dic_one = {'十':'1','二十':'2','三十':'3',None:''}
df_res = df_new['ID'].str.extract(r'(?P<姓名>[a-zA-Z]+):(?P<国籍>[\d])国人,性别(?P<性别>[\w]),生于(?P<出生年>[\w]{4})年(?P<出生月>[\w]+)月(?P<出生日>[\w]+)日')
df_res['出生年'] = df_res['出生年'].str.replace(r'(\w)+',lambda x:''.join([dic_year[x.group(0)[i]] for i in range(4)]))
df_res['出生月'] = df_res['出生月'].str.replace(r'(?P<one>\w?十)?(?P<two>[\w])',lambda x:dic_one[x.group('one')]+dic_two[x.group('two')]).str.replace(r'0','10')
df_res['出生日'] = df_res['出生日'].str.replace(r'(?P<one>\w?十)?(?P<two>[\w])',lambda x:dic_one[x.group('one')]+dic_two[x.group('two')]).str.replace(r'^0','10')
df_res.head()
姓名国籍性别出生年出生月出生日
人员编号
1aesfd21942810
2fasefa51985104
3aeagd419461015
4aef41999513
5eaf12010624
【练习二】 现有一份半虚拟的数据集,第一列包含了新型冠状病毒的一些新闻标题,请解决以下问题:
(a)选出所有关于北京市和上海市新闻标题的所在行。
pd.read_csv('data/String_data_two.csv').head()
col1col2col3
0鄂尔多斯市第2例确诊患者治愈出院19363.6923
1云南新增2例,累计124例-67-152.281
2武汉协和医院14名感染医护出院-86325.6221
3山东新增9例,累计307例-74-204.9313
4上海开学日期延至3月-954.05
a=pd.read_csv('data/String_data_two.csv').convert_dtypes()
a[a['col1'].str.contains(r'上海') |a['col1'].str.contains(r'北京')].head()#
col1col2col3
4上海开学日期延至3月-954.05
5北京新增25例确诊病例,累计确诊253例-4-289.1719
6上海新增10例,累计243例2-73.7105
36上海新增14例累计233例-55-83
40上海新增14例累计233例-88-99
参考答案
df = pd.read_csv('data/String_data_two.csv')
df.head()
df[df['col1'].str.contains(r'[北京]{2}|[上海]{2}')].head()
col1col2col3
4上海开学日期延至3月-954.05
5北京新增25例确诊病例,累计确诊253例-4-289.1719
6上海新增10例,累计243例2-73.7105
36上海新增14例累计233例-55-83
40上海新增14例累计233例-88-99
(b)求col2的均值。
b=pd.read_csv('data/String_data_two.csv').convert_dtypes()
b['col2'][~ b['col2'].str.contains(r'^-?\d+$')]
309    0-
396    9`
485    /7
Name: col2, dtype: string
# #.astype('float')
# a['col2'].apply(lambda x:float(x))
b['col2'][~ b['col2'].str.contains(r'^-?\d+$')]=['0','9','7']

b['col2'].apply(lambda x: int(x)).mean()
-0.984
参考答案
df['col2'][~(df['col2'].str.replace(r'-?\d+','True')=='True')] #这三行有问题
309    0-
396    9`
485    /7
Name: col2, dtype: object
或者
def is_number(x):
    try:
        float(x)
        return True
    except:
        return False
df[~df.col2.map(is_number)]
df.loc[[309,396,485],'col2'] = [0,9,7]
df['col2'].astype('int').mean()
-0.984
(c)求col3的均值。
c=pd.read_csv('data/String_data_two.csv').convert_dtypes()
c.columns
Index(['col1', 'col2', 'col3  '], dtype='object')
c.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 500 entries, 0 to 499
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   col1    500 non-null    string
 1   col2    500 non-null    string
 2   col3    500 non-null    string
dtypes: string(3)
memory usage: 11.8 KB
c['col3  '][~ c['col3  '].str.contains(r'^-?\d+(.)?(\d+)?$')]=['355.3567','9056.2253','3534.6554']
c['col3  '].astype('float').mean()
F:\dev\anaconda\envs\python35\lib\site-packages\pandas\core\strings.py:1954: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
  return func(self, *args, **kwargs)





24.707484999999988
参考答案
df.columns = df.columns.str.strip()
df.columns
Index(['col1', 'col2', 'col3'], dtype='object')
df['col3'][~(df['col3'].str.replace(r'-?\d+\.?\d+','True')=='True')]
28      355`.3567
37             -5
73              1
122    9056.\2253
332    3534.6554{
370             7
Name: col3, dtype: object
或者
def is_number(x):
    try:
        float(x)
        return True
    except:
        return False
df[~df.col3.map(is_number)]
df.loc[[28,122,332],'col3'] = [355.3567,9056.2253, 3534.6554]
df['col3'].astype('float').mean()
24.707484999999988

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值