简体   繁体   中英

Replace Column in Data Frame from Lookup of other Data Frame

Hi, I have two data frames, one containing:-

<p>Country Code | Population </p>

and another containing:-

<p>Country Code | Country Name. </p>

I want to do a replace in the first data frame so that CountryCode = CountryName where applicable. Important to note if the lookup failed, ie no CountryCode matched in second data frame I would like to keep as is. Any ideas how this can be done?

Sample:-

<p>Country Code | Population </p>
<p>RSA | 100</p>
<p>POL | 50</p>

<p> Country Code | Country Name </p>
<p> RSA | South Africa </p>

Expected Output for DF1

<p> Country Code | Population </p>
<p> South Africa | 100 </p>
<p> POL | 50 </p>

If your 2 dataframes are df1 and df2 respectively, this is one way:

s = df2.set_index('Country Code')['Country Name']
df1['Country Code'] = df1['Country Code'].map(s).fillna(df1['Country Code'])

This is also possible via replace , but map + fillna is generally more efficient.

Use replace by Series created by set_index :

s = DF2.set_index('Country Code')['Country Name']
DF1['Country Code'] = DF1['Country Code'].replace(s)
print (DF1)
   Country Code  Population
0  South Africa         100
1           POL          50

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