结论
- apply:用在dataframe上,用于对row或者column进行计算;
- applymap:用于dataframe上,是元素级别的操作;
- map:(其实是python自带的)用于series上,是元素级别的操作。
apply函数
apply函数:pandas里面所有函数中自由度最高的函数。该函数如下:
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
该函数最有用的是第一个参数,这个参数是函数,相当于C/C++的函数指针。
这个函数需要自己实现,函数的传入参数根据 axis
来定,比如 axis = 1
,就会把一行数据作为Series的数据
结构传入给自己实现的函数中,我们在函数中实现对Series不同属性之间的计算,返回一个结果,则apply函数
会自动遍历每一行DataFrame的数据,最后将所有结果组合成一个Series数据结构并返回。
import pandas as pd
import numpy as np
from pandas import DataFrame
from pandas import Series
df1= DataFrame({
"sales1":[-1,2,3],
"sales2":[3,-5,7],
})
print(df1)
print(df1.apply(lambda x :x.max()-x.min(),axis=1))
# 0 4
# 1 7
# 2 4
# dtype: int64
print(df1.apply(lambda x :x.max()-x.min(),axis=0))
# sales1 4
# sales2 12
# dtype: int64
applymap函数
当我们要对数据框(DataFrame)的每一个数据进行操作时用applymap(),返回结果是DataFrame格式
df1.applymap(lambda x : 1 if x>0 else 0)
# 从下面的结果可以看出,我们使用了applymap函数之后,
# 系统自动对每一个数据进行判断,判断之后输出结果
map函数
当我们要对Series的每一个数据进行操作时用map()
df1.sales1.map(lambda x : 1 if x>0 else 0)
输出结果
# 0 0
# 1 1
# 2 1
# Name: sales1, dtype: int64