Pandas中的map(), apply()和applymap()的区别

将一个自定义的函数应用到Pandas的数据结构中可以使用map(), apply()或者applymap(),它们的区别在于应用的对象不同。

apply()和applymap()是DataFrame结构中的函数,Series中没有。它们的区别在于,apply()将一个函数作用于DataFrame中的每个行或者列,而applymap()是将函数做用于DataFrame中的所有元素(elements)。

apply() 当想让方程作用在一维的向量上时,可以使用apply来完成
Python
In [6]: from <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/pandas" title="View all posts in pandas" target="_blank">pandas</a></span> import DataFrame In [7]: import numpy as np In [8]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Ut ...: ah', 'Ohio', 'Texas', 'Oregon']) In [9]: frame Out[9]: b d e Utah 1.646124 -0.843271 -0.253782 Ohio -0.965261 0.254368 -0.173054 Texas -0.927661 -0.558319 -0.838144 Oregon -1.410459 -1.901251 1.199630 In [10]: f = lambda x: x.max() - x.min() In [11]: frame.apply(f) Out[11]: b 3.056583 d 2.155619 e 2.037774 dtype: float64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   In [ 6 ] : from pandas import DataFrame
 
   In [ 7 ] : import numpy as np
 
   In [ 8 ] : frame = DataFrame ( np . random . randn ( 4 , 3 ) , columns = list ( 'bde' ) , index = [ 'Ut
      ...: ah' , 'Ohio' , 'Texas' , 'Oregon' ] )
 
   In [ 9 ] : frame
   Out [ 9 ] :
                   b          d          e
   Utah      1.646124 - 0.843271 - 0.253782
   Ohio    - 0.965261    0.254368 - 0.173054
   Texas    - 0.927661 - 0.558319 - 0.838144
   Oregon - 1.410459 - 1.901251    1.199630
 
   In [ 10 ] : f = lambda x : x . max ( ) - x . min ( )
 
   In [ 11 ] : frame . apply ( f )
   Out [ 11 ] :
   b      3.056583
   d      2.155619
   e      2.037774
   dtype : float64
 
map()只要是作用将函数作用于一个Series的每一个元素,用法如下所示

map() 是一个Series的函数,DataFrame结构中没有map()。map()将一个自定义函数应用于Series结构中的每个元素(elements)。

Python
In [122]: frame['e'].map(format) Out[122]: Utah 1.28 Ohio -1.55 Texas 0.20 Oregon -0.31 Name: e, dtype: object
1
2
3
4
5
6
7
8
   In [ 122 ] : frame [ 'e' ] . map ( format )
   Out [ 122 ] :
   Utah        1.28
   Ohio        - 1.55
   Texas        0.20
   Oregon      - 0.31
   Name : e , dtype : object
 

applymap()如果想让方程作用于DataFrame中的每一个元素,可以使用applymap().用法如下所示

Python
In [120]: format = lambda x: '%.2f' % x In [121]: frame.applymap(format) Out[121]: b d e Utah -0.03 1.08 1.28 Ohio 0.65 0.83 -1.55 Texas 0.51 -0.88 0.20 Oregon -0.49 -0.48 -0.31
1
2
3
4
5
6
7
8
9
10
In [ 120 ] : format = lambda x : '%.2f' % x
 
In [ 121 ] : frame . applymap ( format )
Out [ 121 ] :
             b        d        e
Utah      - 0.03    1.08    1.28
Ohio      0.65    0.83    - 1.55
Texas      0.51    - 0.88    0.20
Oregon    - 0.49    - 0.48    - 0.31
 



  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值