简体   繁体   English

Pandas迭代行并找到列名

[英]Pandas iterate over rows and find the column names

i have a two dataframes as: 我有两个数据帧:

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"]})

i want to itirate on df2 "Cities" column to find the cities on my (df) and append the country of the city (df column names) to the df2 country column 我想在df2“城市”列上找到我的(df)上的城市,并将城市的国家/地区(df列名称)附加到df2国家/地区列

Use melt with map by dictionary: 通过字典使用map melt

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

After melting and renaming the first dataframe: 融化并重命名第一个数据帧后:

df1 = df.melt().rename(columns={'variable': 'Country', 'value': 'Cities'})

the solution is a simple merge: 解决方案是一个简单的合并:

df2 = df2[['Cities']].merge(df1, on='Cities')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM