- 一、文本数据处理
- 1.1 处理字符串型数据列的进化
- 1.1.1 循环处理字符串型数据列:for
- 1.1.2映射函数处理字符串型数据列:map / apply
- 1.1.3、pandas专有方法处理字符串型数据列:.str
- 1.2 字符串列.str常用操作
- 1. 2.1 字符串替换
- 1.2.2 字符串分割
- 1.2.3 字符串链式操作:分割+取值
- 1.2.4 分割字符串列为独立的DF
- 1.2.5 测试是否包含子串
- 1.2.6 判断字符串型数据列的值,是否在列表中(.str没有的方法怎么办)
- 1.3 字符串列.str所有方法
- 二、匿名函数
- 2.1 什么是匿名函数
- 2.2 单返回值的普通函数转换为匿名函数
- 2.3 匿名函数作为参数传递
- 2.4 匿名函数的参数个数及列表推导式
- 2.5 匿名函数与映射函数配合使用
- 2.6 Pandas中使用匿名函数
- 三、映射函数
- 3.1 python内置函数map
- 3.1.1 map配合普通函数
- 3.1.2 map配合匿名函数
- 3.1.3 map对Pandas的Series的元素级操作
- 3.2 Pandas的Dataframe元素级映射函数applymap()
- 3.3 Pandas的万能映射函数apply()
视频讲解:
【Python百日基础系列】Pandas文本及匿名和映射函数
一、文本数据处理 1.1 处理字符串型数据列的进化 1.1.1 循环处理字符串型数据列:for缺点:代码多,速度慢
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
for i in df.index:
print(df.loc[i, '职位'], type(df.loc[i, '职位']))
df.loc[i, '职位'] = df.loc[i, '职位'].replace('数据', '数据库')
print(df)
1.1.2映射函数处理字符串型数据列:map / apply
缺点:无法处理Na值,速度较慢
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df['职位'] = df['职位'].map(lambda x: x.replace('数据', '数据库'))
df['职位'] = df['职位'].apply(lambda x: x.replace('数据', '数据库'))
# df['领域'] = df['领域'].apply(lambda x: x.replace('网', '')) # AttributeError: 'float' object has no attribute 'replace'
print(df)
1.1.3、pandas专有方法处理字符串型数据列:.str
优点:代码简洁,可读性强,速度快
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df['职位'] = df['职位'].str.replace('数据', '数据库')
print(df)
1.2 字符串列.str常用操作
Pandas中文网说明:
http://www.pypandas.cn/docs/user_guide/text.html
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df['职位'] = df['职位'].str.replace('数据', '数据库')
print(df)
1.2.2 字符串分割
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df['领域'] = df['领域'].str.split(',')
print(df)
1.2.3 字符串链式操作:分割+取值
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df['领域s'] = df['领域'].str.split(',')
df['领域s1'] = df['领域'].str.split(',').str.get(0)
df['领域s2'] = df['领域'].str.split(',').str[1]
print(df)
1.2.4 分割字符串列为独立的DF
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
df1 = df['领域'].str.split(',', expand=True)
print(df)
print(df1)
1.2.5 测试是否包含子串
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
print(df)
print(df['职位'].str.contains('建模'))
1.2.6 判断字符串型数据列的值,是否在列表中(.str没有的方法怎么办)
df = pd.read_csv('data.csv', usecols=['positionId', 'positionName', 'industryField', 'salary', 'score', 'matchScore'])
df.columns = ['id', '职位', '领域', '薪资', '热度', '得分']
print(df)
print(df['职位'].apply(lambda x: x in ['数据分析', 'BI数据分析师']))
1.3 字符串列.str所有方法
注意,下表的所有方法都是Pandas重新封装的专有方法,不是字符串原生的方法。
这些方法可以作用在字符串型数据列(Series)上,必须是**Series.str.func().str.func()**的格式。
| 方法 | 描述 |
|---|---|
| cat() | 连接字符串 |
| split() | 在分隔符上分割字符串 |
| rsplit() | 从字符串末尾开始分隔字符串 |
| get() | 索引到每个元素(检索第i个元素) |
| join() | 使用分隔符在系列的每个元素中加入字符串 |
| get_dummies() | 在分隔符上分割字符串,返回虚拟变量的Dataframe |
| contains() | 如果每个字符串都包含pattern / regex,则返回布尔数组 |
| replace() | 用其他字符串替换pattern / regex的出现 |
| repeat() ) | 重复值(s.str.repeat(3)等同于x * 3 t2 ) |
| pad() | 将空格添加到字符串的左侧,右侧或两侧 |
| center() | 相当于str.center |
| ljust() | 相当于str.ljust |
| rjust() | 相当于str.rjust |
| zfill() | 等同于str.zfill |
| wrap() | 将长长的字符串拆分为长度小于给定宽度的行 |
| slice() | 切分Series中的每个字符串 |
| slice_replace() | 用传递的值替换每个字符串中的切片 |
| count() | 计数模式的发生 |
| startswith() | 相当于每个元素的str.startswith(pat) |
| endswith() | 相当于每个元素的str.endswith(pat) |
| findall() | 计算每个字符串的所有模式/正则表达式的列表 |
| match() | 在每个元素上调用re.match,返回匹配的组作为列表 |
| extract() | 在每个元素上调用re.search,为每个元素返回一行Dataframe,为每个正则表达式捕获组返回一列 |
| extractall() | 在每个元素上调用re.findall,为每个匹配返回一行Dataframe,为每个正则表达式捕获组返回一列 |
| len() | 计算字符串长度 |
| normalize() | 返回Unicode标准格式。相当于unicodedata.normalize |
| strip() | 等价于str.strip |
| rstrip() | 等价于str.rstrip |
| lstrip() | 等价于str.lstrip |
| partition() | 等价于 str.partition |
| rpartition() | 等价于 str.rpartition |
| lower() | 等价于 str.lower |
| casefold() | 等价于 str.casefold |
| upper() | 等价于 str.upper |
| find() | 等价于str.find |
| rfind() | 等价于 str.rfind |
| index() | 等价于 str.index |
| rindex() | 等价于 str.rindex |
| capitalize() | 等价于 str.capitalize |
| swapcase() | 等价于 str.swapcase |
| normalize() | 返回Unicode 标注格式。等价于 unicodedata.normalize |
| translate() | 等价于 str.translate |
| isalnum() | 等价于 str.isalnum |
| isalpha() | 等价于 str.isalpha |
| isdigit() | 等价于 str.isdigit |
| isspace() | 等价于 str.isspace |
| islower() | 等价于 str.islower |
| isupper() | 等价于 str.isupper |
| istitle() | 等价于 str.istitle |
| isnumeric() | 等价于 str.isnumeric |
| isdecimal() | 等价于 str.isdecimal |
- 定义
在Python中,不通过def来声明函数名字,而是通过lambda关键字来定义的函数称为匿名函数。
lambda函数能接收任何数量(可以是0个)的参数,但只能返回一个表达式的值。 - 语法:
lambda args:func
- 使用场景:
- 需要将一个函数对象作为参数来传递时,可以直接定义一个lambda函数(作为函数的参数或返回值)
- 要处理的业务符合lambda函数的情况(任意多个参数和一个返回值),并且只有一个地方会使用这个函数,不会在其他地方重用,可以使用lambda函数
- 与一些Python的内置函数配合使用,提高代码的可读性
# 普通函数
def square_difference(a,b):
""" 平方差函数 """
return a**2 - b**2
print(square_difference(2,3))
# 匿名函数
lf = lambda a, b: a**2 - b**2
print(lf(2,3))
# 查看函数对象
print(type(lf))
print(type(square_difference))
# 匿名函数+映射函数+列表函数
print(list(map(lambda a,b: a**2 - b**2, [2], [3])))
输出结果:
-5
-5
[-5]
lambda适用于多个参数、一个返回值的情况,可以用一个变量来接收函数对象,执行这个函数对象的结果与执行一个普通函数的结果一样,但是lambda函数比普通函数更简洁。
2.3 匿名函数作为参数传递def square_difference(a,b, lf):
""" 平方差函数 """
return a**2 - b**2 + lf(a,b)
print(square_difference(2, 3, lambda a, b: a**2 - b**2))
输出结果:
-10
2.4 匿名函数的参数个数及列表推导式
# 0个参数 lf0 = lambda : 365 # 1个参数 lf1 = lambda a: a**2 # 多个参数 lf3 = lambda a, b, c: a**2 - b**2 + c**3 # 三元表达式 lf4 = lambda a: a**2 if a%2 else a**5 # a%2 奇数True,偶数False # 列表推导式 lf5 = lambda a: [a**i for i in range(5)] # 列表推导式带if判断 lf6 = lambda a: [a**i for i in range(5) if i%2] # 列表推导式带if-else判断 lf7 = lambda a: [a**i if i%2 else str(a)+'**'+str(i) for i in range(5)] print(lf0) print(lf0()) print(lf1(10)) print(lf3(10,20,30)) print(lf4(7)) print(lf5(2)) print(lf6(2)) print(lf7(3)) 输出结果:2.5 匿名函数与映射函数配合使用at 0x00000147CA0E9EA0> 365 100 26700 49 [1, 2, 4, 8, 16] [2, 8] ['3**0', 3, '3**2', 27, '3**4']
lst = [1, 2, 3, 4, 5, 6]
l_map = map(lambda x: {str(x): x**2}, lst)
print(l_map)
print(list(l_map))
输出结果:
2.6 Pandas中使用匿名函数
# 跳过偶数行,取奇数行
df = pd.read_csv('data.csv', skiprows=lambda x: x%2)
print(df)
# 读取列名在列表内的数据列
lst = ['positionId','test','positionName', 'test1','salary']
df = pd.read_csv('data.csv', usecols=lambda x: x in lst)
print(df)
三、映射函数
3.1 python内置函数map
语法:map(function, iterable, …)
- function,函数名,可以为匿名函数
- iterable,参数为可迭代对象,参数个数要与前面的function中的参数个数一致
- 返回值为一个map迭代器,可以用list()函数转化为列表
def square_difference(a,b):
""" 平方差函数 """
return a**2 - b**2
print(list(map(square_difference, [2], [3])))
输出结果:
[-5]
3.1.2 map配合匿名函数
print(list(map(lambda a, b: a**2 - b**2, [2], [3]))) 输出结果: [-5]3.1.3 map对Pandas的Series的元素级操作
注:不能对Dataframe进行元素级操作
df = pd.Dataframe(np.arange(16).reshape(4,4),
index = list('abcd'),
columns= list('一二三四'))
df['五'] = df['四'].map(lambda x: x*-1)
print(df)
输出结果:
一 二 三 四 五
a 0 1 2 3 -3
b 4 5 6 7 -7
c 8 9 10 11 -11
d 12 13 14 15 -15
3.2 Pandas的Dataframe元素级映射函数applymap()
注:不能对Series进行元素级操作
df = pd.Dataframe(np.arange(16).reshape(4,4),
index = list('abcd'),
columns= list('一二三四'))
df = df.applymap(lambda x: x*-1)
print(df)
输出结果:
一 二 三 四
a 0 -1 -2 -3
b -4 -5 -6 -7
c -8 -9 -10 -11
d -12 -13 -14 -15
3.3 Pandas的万能映射函数apply()
- apply()对Series的元素级操作,可替代map()
df = pd.Dataframe(np.arange(16).reshape(4,4),
index = list('abcd'),
columns= list('一二三四'))
df['五'] = df['四'].apply(lambda x: x*-1)
print(df)
输出结果:
一 二 三 四 五
a 0 1 2 3 -3
b 4 5 6 7 -7
c 8 9 10 11 -11
d 12 13 14 15 -15
- apply()对Dataframe的元素级操作,可替代applymap()
df = pd.Dataframe(np.arange(16).reshape(4,4),
index = list('abcd'),
columns= list('一二三四'))
df = df.apply(lambda x: x*-1)
print(df)
输出结果:
一 二 三 四
a 0 -1 -2 -3
b -4 -5 -6 -7
c -8 -9 -10 -11
d -12 -13 -14 -15
- apply()对Dataframe进行按行(横向axis=1)或按列(纵向axis=0,默认)聚合操作,map()和applymap()均无法进行
df = pd.Dataframe(np.arange(16).reshape(4,4),
index = list('abcd'),
columns= list('一二三四'))
df0 = df.apply(lambda x: x.sum(), axis=0)
df1 = df.apply(lambda x: x.sum(), axis=1)
print(df)
print(df0)
print(df1)
输出结果:
一 二 三 四
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
一 24
二 28
三 32
四 36
dtype: int64
a 6
b 22
c 38
d 54
dtype: int64



