gpt4 book ai didi

python-3.x - 根据匹配值从其他数据框中复制列

转载 作者:行者123 更新时间:2023-12-05 03:49:48 25 4
gpt4 key购买 nike

我有两个数据框,一个有 iso 代码和国家名称另一个只有国家名称。

如果值为 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:只能比较相同标记的 Series 对象

最佳答案

您可以使用 DataFrame.merge在从 df1 中删除重复值后,leftdf2df1 合并:

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

或者,您可以使用 Series.map根据 iso 代码将 Countrydf1 映射到 df2:

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

关于python-3.x - 根据匹配值从其他数据框中复制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63762337/

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