zoukankan      html  css  js  c++  java
  • pandas 的 map()

      先来几句麦金尼著作里的话:

    For many datasets, you may wish to perform some transformation based on the values in an array, Series, or column in a DataFrame.

    The map method on a Series accepts a function or dict-like object containing a mapping.

    Using map is a convenient way to perform element-wise transformations and other data cleaning–related operations.

     

    使用 map 可以实现 Series 的元素级转换。

    示例如下:

    import pandas as pd
    
    df = pd.DataFrame([['乔峰', 'I', 95, '降龙十八掌', '乞丐'],
                       ['虚竹', 'II', 93, '天上六阳掌', '和尚'],
                       ['段誉', 'II', 92, '六脉神剑', '王侯'],
                       ['包不同', 'V', 65, '胡搅蛮缠', '仆人'],
                       ['康敏', 'X', 10, '惑夫妒人', '坏女人']],
                       columns=['name', 'grade', 'score', 'skill', 'calss'])
    df

    输出为:

     

     定义一个 grade 的映射字典,转换 grade 列的罗马数字为阿拉伯数字

    grade_mapping = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5,
                     'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10}
    df.grade = df['grade'].map(grade_mapping)
    df

    输出如下:

     

     定义一个逆映射

    inv_grade_mapping = dict((v, k) for k, v in grade_mapping.items())
    inv_grade_mapping

    输出如下:

     

     将 df 中的 grade重新转换过为罗马数字:

    df.grade = df['grade'].map(inv_grade_mapping)
    df

    输出如下:

     

    利用 pandas 的 map 方法就可以实现类似 R语言里 factor 的功能。

     

  • 相关阅读:
    html5之服务器推送事件
    浅谈js之this对象
    浅谈js之事件处理
    浅谈js之ajax
    浅谈js之事件流
    浅谈js之闭包
    浅谈JS引用类型之Array类型
    关于window.onload的一些小理解
    web渗透测试中WAF绕过讲解(二)基于HTTP协议绕过
    web渗透测试中WAF绕过讲解(一)
  • 原文地址:https://www.cnblogs.com/shanger/p/12925052.html
Copyright © 2011-2022 走看看