从其他数据框查找中替换数据框中的列 [英] Replace Column in Data Frame from Lookup of other Data Frame
本文介绍了从其他数据框查找中替换数据框中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据框,其中一个包含:-
Hi, I have two data frames, one containing:-
<p>Country Code | Population </p>
和另一个包含:-
<p>Country Code | Country Name. </p>
我想在第一个数据框中进行替换,以便在适用的情况下使用CountryCode = CountryName.重要的是要注意查找是否失败,即我想保持原样的第二个数据帧中没有匹配的CountryCode.任何想法如何做到这一点?
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?
样品:-
<p>Country Code | Population </p>
<p>RSA | 100</p>
<p>POL | 50</p>
<p> Country Code | Country Name </p>
<p> RSA | South Africa </p>
DF1的预期输出
<p> Country Code | Population </p>
<p> South Africa | 100 </p>
<p> POL | 50 </p>
推荐答案
如果您的2个数据帧分别为df1
和df2
,则这是一种方法:
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'])
这也可以通过replace
来实现,但是map
+ fillna
通常更有效.
This is also possible via replace
, but map
+ fillna
is generally more efficient.
这篇关于从其他数据框查找中替换数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文