Python - 基于另一个数据帧匹配替换数据帧中的值 [英] Python - replace values in dataframe based on another dataframe match

查看:60
本文介绍了Python - 基于另一个数据帧匹配替换数据帧中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 个名为 A 和 B 的 Python 数据框 2,如下所示.如何根据列 ID 和来自 B 的月份的匹配替换数据框 A 中的列值?有什么想法吗?

Suppose that I have 2 Python data frame2 named A and B like shown below. How could I replace column Value in data frame A based on the matches of columns ID and Month from B? Any ideas?

谢谢

数据框 A:

ID  Month   City    Brand   Value
1   1   London  Unilever    100
1   2   London  Unilever    120
1   3   London  Unilever    150
1   4   London  Unilever    140
2   1   NY  JP Morgan   90
2   2   NY  JP Morgan   105
2   3   NY  JP Morgan   100
2   4   NY  JP Morgan   140
3   1   Paris   Loreal  60
3   2   Paris   Loreal  75
3   3   Paris   Loreal  65
3   4   Paris   Loreal  80
4   1   Tokyo   Sony    100
4   2   Tokyo   Sony    90
4   3   Tokyo   Sony    85
4   4   Tokyo   Sony    80

数据框 B:

ID  Month   Value
2   1   100
3   3   80

推荐答案

使用 merge 与左连接并通过 fillna:

df = df1.merge(df2, on=['ID', 'Month'], how='left', suffixes=('_',''))
df['Value'] = df['Value'].fillna(df['Value_']).astype(int)
df = df.drop('Value_', axis=1)
print (df)
    ID  Month    City      Brand  Value
0    1      1  London   Unilever    100
1    1      2  London   Unilever    120
2    1      3  London   Unilever    150
3    1      4  London   Unilever    140
4    2      1      NY  JP Morgan    100
5    2      2      NY  JP Morgan    105
6    2      3      NY  JP Morgan    100
7    2      4      NY  JP Morgan    140
8    3      1   Paris     Loreal     60
9    3      2   Paris     Loreal     75
10   3      3   Paris     Loreal     80
11   3      4   Paris     Loreal     80
12   4      1   Tokyo       Sony    100
13   4      2   Tokyo       Sony     90
14   4      3   Tokyo       Sony     85
15   4      4   Tokyo       Sony     80

这篇关于Python - 基于另一个数据帧匹配替换数据帧中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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