Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - 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, i.e. 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...