pandas :将多列映射到一列 [英] pandas: map multiple columns to one column

查看:83
本文介绍了 pandas :将多列映射到一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列要使用相同的字典映射到一个新列(如果字典中没有匹配的键,则返回 0).

I have two columns that I want to map to a single new column using the same dictionary (and return 0 if there is no matching key in the dictionary).

>> codes = {'2':1,
            '31':1,
            '88':9,
            '99':9}

>> df[['driver_action1','driver_action2']].to_dict()    
{'driver_action1': {0: '1',
  1: '1',
  2: '77',
  3: '77',
  4: '1',
  5: '4',
  6: '2',
  7: '1',
  8: '77',
  9: '99'},
 'driver_action2': {0: '31',
  1: '99',
  2: '31',
  3: '55',
  4: '1',
  5: '5',
  6: '99',
  7: '2',
  8: '4',
  9: '99'}}

我以为我可以这样做:

>> df['driver_reckless_remapped'] = df[['driver_action1','driver_action2']].applymap(lambda x: codes.get(x,0))

预期输出:

  driver_action1 driver_action2   driver_reckless_remapped
0              1             31                          1
1              1             99                          9
2             77             31                          1
3             77             55                          0
4              1              1                          0
5              4              5                          0
6              2             99                          1
7              1              2                          1
8             77              4                          0
9             99             99                          9

但我得到:

TypeError: ("'dict' object is not callable", 'occurred at index driver_action1')

没有办法将多列映射到一个新列吗?

Is there no way to map multiple columns to one new column?

推荐答案

IIUC 你可以使用 combine_first() 方法

IIUC you can use combine_first() method

df['new'] =  = \
    df.driver_action1.map(codes).combine_first(df.driver_action2.map(codes)).fillna(0)

检查:

In [106]: df['new'] = df.driver_action1.map(codes).combine_first(df.driver_action2.map(codes)).fillna(0)

In [107]: df
Out[107]:
  driver_action1 driver_action2 driver_reckless_remapped  new
0              1             31                        1  1.0
1              1             99                        9  9.0
2             77             31                        1  1.0
3             77             55                        0  0.0
4              1              1                        0  0.0
5              4              5                        0  0.0
6              2             99                        1  1.0
7              1              2                        1  1.0
8             77              4                        0  0.0
9             99             99                        9  9.0

这篇关于 pandas :将多列映射到一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆