企业项目管理、ORK、研发管理与敏捷开发工具平台

网站首页 > 精选文章 正文

Pandas中的宝藏函数-map

wudianyun 2024-12-23 10:10:06 精选文章 62 ℃

来源:AI入门学习

作者:小伍哥

pandas中的map类似于Python内建的map()方法,pandas中的map()方法将函数、字典索引或是一些需要接受单个输入值的特别的对象与对应的单个列的每一个元素建立联系并串行得到结果。

这里我们想要得到gender列的F、M转换为女性、男性的新列,可以有以下几种实现方式先构造一个数据集

map()函数可以用于Series对象或DataFrame对象的一列,接收函数作为或字典对象作为参数,返回经过函数或字典映射处理后的值。

用法:Series.map(arg, na_action=None)

参数:

arg : function, dict, or Series

Mapping correspondence.

na_action : {None, ‘ignore’}, default None

If ‘ignore’, propagate NaN values, without passing them to the mapping

correspondence.

返回:Pandas Series with same as index as caller

官方:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html

首先构建一个数据集,下面进行案例应用

data = pd.DataFrame(
{"name":['Jack', 'Alice', 'Lily', 'Mshis', 'Gdli', 'Agosh', 'Filu', 'Mack', 'Lucy', 'Pony'],
"gender":['F', 'M', 'F', 'F', 'M', 'F', 'M', 'M', 'F', 'F'],
"age":[25, 34, 49, 42, 28, 23, 45, 21, 34, 29]}
                     ) 
data
 name gender  age
0   Jack      F   25
1  Alice      M   34
2   Lily      F   49
3  Mshis      F   42
4   Gdli      M   28
5  Agosh      F   23
6   Filu      M   45
7   Mack      M   21
8   Lucy      F   34
9   Pony      F   29

1 字典映射

这里我们编写F、M与女性、男性之间一一映射的字典,再利用map()方法来得到映射列:

#定义F->女性,M->男性的映射字典
gender2xb = {'F': '女性', 'M': '男性'}


#利用map()方法得到对应gender列的映射列
data.gender.map(gender2xb)
0    女性
1    男性
2    女性
3    女性
4    男性
5    女性
6    男性
7    男性
8    女性
9    女性

2 lambda函数

这里我们向map()中传入lambda函数来实现所需功能:

#因为已经知道数据gender列性别中只有F和M所以编写如下lambda函数
data.gender.map(lambda x:'女性' if x == 'F' else '男性')
0    女性
1    男性
2    女性
3    女性
4    男性
5    女性
6    男性
7    男性
8    女性
9    女性


#年龄的平方
data.age.map(lambda x: x**2)
0     625
1    1156
2    2401
3    1764
4     784
5     529
6    2025
7     441
8    1156
9     84

3 常规函数

map函数,也可以传入通过def定义的常规函数,看看下面的案例

#性别转换
def gender_to_xb(x):
    return '女性' if x == 'F' else '男性'
    
data.gender.map(gender_to_xb)
0    女性
1    男性
2    女性
3    女性
4    男性
5    女性
6    男性
7    男性
8    女性
9    女性

4 特殊对象

map()可以传入的内容有时候可以很特殊,如下面的例子:一些接收单个输入值且有输出的对象也可以用map()方法来处理:

data.gender.map("This kid's gender is {}".format)
0    This kid's gender is F
1    This kid's gender is M
2    This kid's gender is F
3    This kid's gender is F
4    This kid's gender is M
5    This kid's gender is F
6    This kid's gender is M
7    This kid's gender is M
8    This kid's gender is F
9    This kid's gender is F

map()中的参数na_action,类似R中的na.action,取值为None或ingore,用于控制遇到缺失值的处理方式,设置为ingore时串行运算过程中将忽略Nan值原样返回。

s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
 s
0      cat
1      dog
2      NaN
3   rabbit

na_action为默认值的情况

s.map('I am a {}'.format)
0       I am a cat
1       I am a dog
2       I am a nan
3    I am a rabbit

na_action为ignore的情况

s.map('I am a {}'.format, na_action='ignore')0 I am a cat1 I am a dog2 NaN3 I am a rabbit

Tags:

最近发表
标签列表