我有两个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
答案 0 :(得分:2)
从df2
删除重复的值后,您可以使用DataFrame.merge
来左合并df1
与df1
:
df2 = df2.merge(df1.drop_duplicates(), left_on='id',
right_on='iso', how='left').drop('iso', 1)
或者,您可以根据Country
代码,使用Series.map
将df1
从df2
映射到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