简体   繁体   中英

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

Use melt with map by dictionary:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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