python apply和map方法的区别_python – Pandas中map,applymap和apply方法的区别

直接从威斯麦肯尼的

Python for Data Analysis书, 132(我强烈推荐这本书):

Another frequent operation is applying a function on 1D arrays to each column or row. DataFrame’s apply method does exactly this:

In [116]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])

In [117]: frame

Out[117]:

b d e

Utah -0.029638 1.081563 1.280300

Ohio 0.647747 0.831136 -1.549481

Texas 0.513416 -0.884417 0.195343

Oregon -0.485454 -0.477388 -0.309548

In [118]: f = lambda x: x.max() - x.min()

In [119]: frame.apply(f)

Out[119]:

b 1.133201

d 1.965980

e 2.829781

dtype: float64

Many of the most common array statistics (like sum and mean) are DataFrame methods,

so using apply is not necessary.

Element-wise Python functions can be used, too. Suppose you wanted to compute a formatted string from each floating point value in frame. You can do this with applymap:

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

The reason for the name applymap is that Series has a map method for applying an element-wise function:

In [122]: frame['e'].map(format)

Out[122]:

Utah 1.28

Ohio -1.55

Texas 0.20

Oregon -0.31

Name: e, dtype: object

总结,应用工作在DataFrame的行/列基础上,applymap在元素方面在DataFrame上工作,并且在一个系列上按元素进行映射。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值