pandas函数应用

《Python for Data Analysis》

函数应用和映射

将函数应用到各列或行所形成的一维数组上 apply方法
In [18]: df1
Out[18]:
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

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

In [20]: df1.apply(f)
Out[20]:
a    8
b    8
c    8
d    8
dtype: int64

In [21]: df1.apply(f,axis=1)
Out[21]:
0    3
1    3
2    3
dtype: int64
元素级的函数 applymap方法
In [22]: format = lambda x: '%.2f' % x

In [23]: df1.applymap(format)
Out[23]:
      a     b      c      d
0  0.00  1.00   2.00   3.00
1  4.00  5.00   6.00   7.00
2  8.00  9.00  10.00  11.00
Series的map方法能够接受一个函数或含有映射关系的字典型对象。
In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: from pandas import Series, DataFrame

In [4]: data = DataFrame({'food':['bacon', 'pulled pork', 'corned beef', 'Bacon'],'ounces
   ...: ':[4,3,7.5,8]})

In [5]: data
Out[5]:
          food  ounces
0        bacon     4.0
1  pulled pork     3.0
2  corned beef     7.5
3        Bacon     8.0

In [6]: meat_to_animal = {
   ...:     'bacon': 'pig',
   ...:     'pulled pork' : 'pig',
   ...:     'corned beef' : 'cow',
   ...:     'Bacon': 'pig'
   ...: }

In [7]: data['animal'] = data['food'].map(str.lower).map(meat_to_animal)

In [8]: data
Out[8]:
          food  ounces animal
0        bacon     4.0    pig
1  pulled pork     3.0    pig
2  corned beef     7.5    cow
3        Bacon     8.0    pig

In [9]: data['food'].map(lambda x: meat_to_animal[x.lower()])
Out[9]:
0    pig
1    pig
2    cow
3    pig
Name: food, dtype: object

使用map是一种实现元素级转换以及其他数据清理工作的便捷方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值