Python - replace values in dataframe based on another dataframe match

随声附和 提交于 2020-08-05 06:12:48

问题


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?

Thanks

Dataframe 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

Dataframe B:

ID  Month   Value
2   1   100
3   3   80

回答1:


Use merge with left join and replace missing values by original values by 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



回答2:


Merge them and then remove the not used fields:

C = pd.merge(A[['ID', 'Month', 'City', 'Brand']],B, on=['ID', 'Month'])
C = C[['ID', 'Month', 'City', 'Brand', 'Value']]

This should work



来源:https://stackoverflow.com/questions/52872582/python-replace-values-in-dataframe-based-on-another-dataframe-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!