gpt4 book ai didi

python - Pandas 遍历行并找到列名

转载 作者:太空狗 更新时间:2023-10-30 01:56:23 25 4
gpt4 key购买 nike

我有两个数据框:

df = pd.DataFrame({'America':["Ohio","Utah","New York"],
'Italy':["Rome","Milan","Venice"],
'Germany':["Berlin","Munich","Jena"]});


df2 = pd.DataFrame({'Cities':["Rome", "New York", "Munich"],
'Country':["na","na","na"]})

我想迭代 df2“城市”列以在我的 (df) 上找到城市并将城市的国家(df 列名称)附加到 df2 国家列

最佳答案

使用meltmap按字典:

df1 = df.melt()
print (df1)
variable value
0 America Ohio
1 America Utah
2 America New York
3 Italy Rome
4 Italy Milan
5 Italy Venice
6 Germany Berlin
7 Germany Munich
8 Germany Jena

df2['Country'] = df2['Cities'].map(dict(zip(df1['value'], df1['variable'])))
#alternative, thanks @Sandeep Kadapa
#df2['Country'] = df2['Cities'].map(df1.set_index('value')['variable'])
print (df2)
Cities Country
0 Rome Italy
1 New York America
2 Munich Germany

关于python - Pandas 遍历行并找到列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54529291/

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