pandas中的applymap和apply

对每列或每行的一维数组应用一个函数是一个常用的操作,这时apply就派上用场了。

In [5]: frame =pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
   ...:  .....: index=['Utah', 'Ohio', 'Texas', 'Oregon'])
   ...:
   ...:
 
In [6]: frame
Out[6]:
               b         d         e
Utah   -1.399209 -0.772885  0.007311
Ohio    0.043153 -0.077433  1.891868
Texas   1.870791  0.963022  1.440104
Oregon -0.528431  0.484408 -0.057004
 
In [7]: frame.apply(lambda x:x.max()-x.min())
Out[7]:
b    3.270000
d    1.735907
e    1.948872
dtype: float64
 
In [8]: frame.apply(lambda x:x.max()-x.min(),axis=1)
Out[8]:
Utah      1.406520
Ohio      1.969301
Texas     0.907769
Oregon    1.012839
dtype: float64
对每个元素进行的操作也经常进行,这时就是applymap派上用场的时候了。

In [9]: frame.applymap(lambda x:'%.2f'%x)
Out[9]:
            b      d      e
Utah    -1.40  -0.77   0.01
Ohio     0.04  -0.08   1.89
Texas    1.87   0.96   1.44
Oregon  -0.53   0.48  -0.06
这个时候axis参数就没有了,因为是操作是对每个元素进行的,而不是之前的apply那样对一维数组进行操作,所以需要指定特定的轴。
--------------------- 
作者:hsc_1 
来源:CSDN 
原文:https://blog.csdn.net/hsc_1/article/details/79596344 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/dss875914213/article/details/87902511