理论:
知识要点
map(function,series)
作用:将funciton函数作用于一个Series的每一个元素
Series:是待分析的数据
function函数:可以是NumPy中的通用函数(np.max、np.mean等)
可以是自定义函数(def function)
优点:不使用循环,代码简洁,效率高
apply()函数
通过apply()将函数应用到行或列上
在DataFrame上操作时注意指定轴的方向,默认axis=0
applymap()函数
通过applymap()将函数应用到对象的元素上,df的维度不变
实验:
第八节 函数应用操作--map
In [1]:
import pandas as pd
import math
import numpy as np
Python的高阶函数map()
In [2]:
l = list(range(10))
print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [8]:
# 对L中的每个元素开根号
# 使用map
result = map(math.sqrt,l)
print(result)
<map object at 0x000001A1D4870640>
In [9]:
# 注意直到取出结果,才会执行操作
list(result)
Out[9]:
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]
Pandas中的map()函数
In [10]:
ser = pd.Series(l)
ser
Out[10]:
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 dtype: int64
In [11]:
#开根号
ser.map(np.sqrt)
Out[11]:
0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000 5 2.236068 6 2.449490 7 2.645751 8 2.828427 9 3.000000 dtype: float64
In [12]:
# 自定义函数
ser.map(lambda x:x**2 + 1)
Out[12]:
0 1 1 2 2 5 3 10 4 17 5 26 6 37 7 50 8 65 9 82 dtype: int64
In [13]:
def func(x):
x1 = x**3
x2 = x1 * 2 + 1
return x2
In [14]:
ser.map(func)
Out[14]:
0 1 1 3 2 17 3 55 4 129 5 251 6 433 7 687 8 1025 9 1459 dtype: int64
In [ ]:
第九节函数应用操作(2)--apply、applymap
In [16]:
df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['col_1','col_2'])
df
Out[16]:
col_1 | col_2 | |
---|---|---|
0 | 0 | 1 |
1 | 2 | 3 |
2 | 4 | 5 |
3 | 6 | 7 |
4 | 8 | 9 |
In [17]:
df.apply(np.sum)
Out[17]:
col_1 20 col_2 25 dtype: int64
In [18]:
# 注意参数axis
df.apply(np.sum,axis=1)
Out[18]:
0 1 1 5 2 9 3 13 4 17 dtype: int64
applymap()
In [20]:
df.applymap(np.sum)
Out[20]:
col_1 | col_2 | |
---|---|---|
0 | 0 | 1 |
1 | 2 | 3 |
2 | 4 | 5 |
3 | 6 | 7 |
4 | 8 | 9 |
实际例子
In [21]:
staff_df = pd.DataFrame([{'姓名':'张三','部门':'研发部'},
{'姓名':'李四','部门':'财务部'},
{'姓名':'赵六','部门':'市场部'}])
staff_df
Out[21]:
姓名 | 部门 | |
---|---|---|
0 | 张三 | 研发部 |
1 | 李四 | 财务部 |
2 | 赵六 | 市场部 |
In [22]:
# 获取姓
staff_df['姓名'].apply(lambda x: x[0])
Out[22]:
0 张 1 李 2 赵 Name: 姓名, dtype: object
In [23]:
staff_df['姓'] = staff_df['姓名'].apply(lambda x: x[0])
staff_df
Out[23]:
姓名 | 部门 | 姓 | |
---|---|---|---|
0 | 张三 | 研发部 | 张 |
1 | 李四 | 财务部 | 李 |
2 | 赵六 | 市场部 | 赵 |
In [ ]: