• Pandas中的宝藏函数-map


    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(
{

    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    女性
    利用map()方法得到对应gender列的映射列添加为新的列
    data.gender.map(lambda x:'女性' if x == 'F' else '男性')
0    女性
1    男性
2    女性
3    女性
4    男性
5    女性
6    男性
7    男性
8    女性
9    女性

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

    #因为已经知道数据gender列性别中只有F和M所以编写如下lambda函数

    在这里插入图片描述

    #年龄的平方
    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(

    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

    参考资料:
    https://zhuanlan.zhihu.com/p/393930947

  • 相关阅读:
    Java List.sort()的使用 和Comparator转换器的实现原理
    adb手机调试常用命令
    力扣:392.判断子序列
    CSS:border作用
    防止 SQL 注入的 PHP PDO 准备语句教程
    Word 文档转换 PDF、图片
    python练习(4)
    1462. 课程表 IV
    视频剪辑的视频素材哪里下载?
    PMI-ACP练习题(20)
  • 原文地址:https://blog.csdn.net/xiaoyurainzi/article/details/126134328