我有两个数据框:
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国家/地区列中
答案 0 :(得分:9)
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
答案 1 :(得分:1)
在熔化并重命名第一个数据帧之后:
df1 = df.melt().rename(columns={'variable': 'Country', 'value': 'Cities'})
解决方案是简单的合并:
df2 = df2[['Cities']].merge(df1, on='Cities')