【问题标题】:Efficiently creating additional columns in a pandas DataFrame using .map()使用 .map() 在 pandas DataFrame 中有效地创建附加列
【发布时间】:2013-05-15 22:12:30
【问题描述】:

我正在分析一个与以下示例形状相似的数据集。我有两种不同类型的数据(abc 数据和 xyz 数据):

   abc1  abc2  abc3  xyz1  xyz2  xyz3
0     1     2     2     2     1     2
1     2     1     1     2     1     1
2     2     2     1     2     2     2
3     1     2     1     1     1     1
4     1     1     2     1     2     1

我想创建一个函数,为数据框中存在的每个 abc 列添加一个分类列。使用列名列表和类别映射字典,我能够得到我想要的结果。

abc_columns = ['abc1', 'abc2', 'abc3']
xyz_columns = ['xyz1', 'xyz2', 'xyz3']
abc_category_columns = ['abc1_category', 'abc2_category', 'abc3_category']
categories = {1: 'Good', 2: 'Bad', 3: 'Ugly'}

for i in range(len(abc_category_columns)):
    df3[abc_category_columns[i]] = df3[abc_columns[i]].map(categories)

print df3

最终结果:

   abc1  abc2  abc3  xyz1  xyz2  xyz3 abc1_category abc2_category abc3_category
0     1     2     2     2     1     2          Good           Bad           Bad
1     2     1     1     2     1     1           Bad          Good          Good
2     2     2     1     2     2     2           Bad           Bad          Good
3     1     2     1     1     1     1          Good           Bad          Good
4     1     1     2     1     2     1          Good          Good           Bad

虽然最后的 for 循环工作正常,但我觉得我应该使用 Python 的 lambda 函数,但似乎无法弄清楚。

有没有更有效的方法来映射动态数量的 abc 类型的列?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以将applymap 与字典get 方法一起使用:

    In [11]: df[abc_columns].applymap(categories.get)
    Out[11]:
       abc1  abc2  abc3
    0  Good   Bad   Bad
    1   Bad  Good  Good
    2   Bad   Bad  Good
    3  Good   Bad  Good
    4  Good  Good   Bad
    

    并将其放到指定的列中:

    In [12]: abc_categories = map(lambda x: x + '_category', abc_columns)
    
    In [13]: abc_categories
    Out[13]: ['abc1_category', 'abc2_category', 'abc3_category']
    
    In [14]: df[abc_categories] = df[abc_columns].applymap(categories.get)
    

    注意:您可以使用列表推导相对有效地构造abc_columns

    abc_columns = [col for col in df.columns if str(col).startswith('abc')]
    

    【讨论】:

    • @AndyHayden,数据帧上的 .applymap 和 pandas 数据帧上的 .map 有什么区别?
    • @yoshiserry applymap 对每个单元格进行处理,而不是每行/列。
    • @AndyHayden 我不确定你的意思,所以 ApplyMap 将该函数应用于每个单元格(即行和列的每个交集),因此基本上是整个数据帧。而 .map 仅针对单行或单列执行此操作?
    • @yoshiserry 是的。 (并且 .apply 与 .map 基本相同,但您会看到它的使用频率更高。)
    猜你喜欢
    • 2022-01-23
    • 2018-11-30
    • 2016-07-14
    • 2019-03-10
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多