基于Series数据结构的操作
pandas.Series.apply
Series.map
对元素进行按元素操作
For element-wise operations
Series.agg
官网注明只能使用聚合类型的操作,如sum,count,mean,std,prod,first,last,可以使用多个
only perform aggregating type operations
但是实际上自定义函数也是可以使用的,也可以args加入多个参数,但是这就抢了apply的饭碗了。
ratings['rating'].agg(minusone,args=(1,))
only perform aggregating type operations
Series.transform
only perform transformating type operation
这里拿一个例子来说明,df调用是按列调用,首先计算了这列的均值和标准差,在把最终计算结果放到对应的位置上去。
df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
... index=pd.date_range('1/1/2000', periods=10))
df.iloc[3:7] = np.nan
>>> df.transform(lambda x: (x - x.mean()) / x.std())
A B C
2000-01-01 0.579457 1.236184 0.123424
2000-01-02 0.370357 -0.605875 -1.231325
2000-01-03 1.455756 -0.277446 0.288967
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 -0.498658 1.274522 1.642524
2000-01-09 -0.540524 -1.012676 -0.828968
2000-01-10 -1.366388 -0.614710 0.005378
Series.apply
官网注明可以应用更复杂的函数到Series,所以当你不知道用啥的时候就apply就对了
For applying more complex functions on a Series.
不仅可以传参数元组,还可以传入参数列表
def add_custom_values(x, **kwargs):
... for month in kwargs:
... x+=kwargs[month]
... return x
>>> series.apply(add_custom_values, june=30, july=20, august=25)
London 95
New York 96
Helsinki 87
dtype: int64
还可以调用np的函数,虽然以上几个都可以,(lll¬ω¬)
ratings['rating'].map(np.log)
基于DataFrame数据结构的操作
pandas.DataFrame.apply
DataFrame.apply
Apply a function row-/column-wise.
既可以按列又可以按行进行计算
这个功能太强大了,默认参数较多,我就不一一列举了,可以点进去自己看
DataFrame.applymap
这个是应用到整个df上的,无默认参数,不多bb,用了就是全部转换
Apply a function elementwise on a whole DataFrame.
另外DataFrame.agg和DataFrame.transform也是存在的,多了默认参数axis和参数元组和参数列表
DataFrame.aggregate(func, axis=0, *args, **kwargs)