gpt4 book ai didi

python - Pandas :将多列映射到一列

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:40 24 4
gpt4 key购买 nike

我有两个列,我想使用同一个字典将它们映射到一个新列(如果字典中没有匹配的键,则返回 0)。

>> 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')

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

最佳答案

您可以使用 IIUC combine_first()方法

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

关于python - Pandas :将多列映射到一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43543634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com