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.
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.