一些Numpy的通用函数对Pandas对象也有效:
In [91]: df = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),index = ['one','two','three','four']) In [92]: df Out[92]: b d e one -0.522310 0.636599 0.992393 two 0.572624 -0.451550 -1.935332 three 0.021926 0.056706 -0.267661 four -2.718122 -0.740140 -1.565448 In [93]: np.abs(df) Out[93]: b d e one 0.522310 0.636599 0.992393 two 0.572624 0.451550 1.935332 three 0.021926 0.056706 0.267661 four 2.718122 0.740140 1.565448
当然,你也可以自定义处理函数,然后使用pandas提供的apply方法,将它应用在每一列:
In [94]: f = lambda x: x.max() - x.min() In [95]: df.apply(f) Out[95]: b 3.290745 d 1.376740 e 2.927725 dtype: float64
当然,可以指定按行应用f,只需要设置axis='columns'。也可以将引用函数的返回值设计为一个Series,这样最终结果会是个DataFrame:
In [96]: df.apply(f, axis='columns') Out[96]: one 1.514703 two 2.507956 three 0.324367 four 1.977981 dtype: float64 In [97]: def f2(x): ...: return pd.Series([x.min(),x.max()], index=['min','max']) In [98]: df.apply(f2) Out[98]: b d e min -2.718122 -0.740140 -1.935332 max 0.572624 0.636599 0.992393
还有更细粒度的apply方法,也就是DataFrame的applymap以及Series的map。它们逐一对每个元素进行操作,而不是整行整列的操作。请体会下面的例子:
In [99]: f3 = lambda x: '%.2f' % x In [100]: df.applymap(f3) Out[100]: b d e one -0.52 0.64 0.99 two 0.57 -0.45 -1.94 three 0.02 0.06 -0.27 four -2.72 -0.74 -1.57 In [101]: df['d'].map(f3) # 获取d列,这是一个Series Out[101]: one 0.64 two -0.45 three 0.06 four -0.74 Name: d, dtype: object
总结:apply()是整行整列的操作,applymap()是逐一对每个元素进行操作。
补充:apply()对于Series数据来说是逐一对元素进行操作,与map()功能一样。