根据匹配值从其他数据框中复制列

时间:2020-09-06 08:48:58

标签: python-3.x pandas dataframe where-clause

我有两个dataFrame,一个带有iso代码和国家/地区名称 另一个只有国名。

如果值df2匹配,我想在df1上添加一个新列,并将国家名称从df1.iso == df2.id开始。

df1

Country      iso    
Afghanistan  AFG       
Afghanistan  AFG       
Afghanistan  AFG       
...

df2

id      
AFG     
AFG     
AFG     
AFG
... 

我尝试过:

post['country'] = pre['Country'].where(pre['iso'] == post['id'])

但是我遇到了错误

ValueError: Can only compare identically-labeled Series objects

1 个答案:

答案 0 :(得分:2)

df2删除重复的值后,您可以使用DataFrame.merge合并df1df1

df2 = df2.merge(df1.drop_duplicates(), left_on='id',
                right_on='iso', how='left').drop('iso', 1)

或者,您可以根据Country代码,使用Series.mapdf1df2映射到iso

df2['Country'] = df2['id'].map(df1.drop_duplicates().set_index('iso')['Country'])

结果:

print(df2)
    id      Country
0  AFG  Afghanistan
1  AFG  Afghanistan
2  AFG  Afghanistan
3  AFG  Afghanistan
相关问题