[英]Filling NaN in a DataFrame Column with Key from a Dictionary by looking up values from a different column
I have a dataset that looks like: 我有一个数据集,看起来像:
> Country Code
> 'Bolivia' NaN
> 'Bolivia, The Republic of' NaN
And I also have a dictionary 我也有字典
> CountryCode = {'BOL':['Bolivia','Bolivia, The Republic of']}
How do I go on about fillna in the dataframe with the respective Key if one of the values is in the dictionary? 如果值之一在字典中,如何使用相应的键继续在数据框中填充fillna?
The desired output is 所需的输出是
> Country Code
> 'Bolivia' 'BOL'
> 'Bolivia, The Republic of' 'BOL'
Thanks for your help! 谢谢你的帮助!
Create reverse dictionary of CountryCode
and map
it with Country
column: 创建的反向字典
CountryCode
和map
与它Country
列:
new_countrycode = {v:key for key,value in CountryCode.items() for v in value}
df['Code'] = df['Country'].map(new_countrycode)
print(df)
Country Code
0 Bolivia BOL
1 Bolivia, The Republic of BOL
print(new_countrycode)
{'Bolivia': 'BOL', 'Bolivia, The Republic of': 'BOL'}
df=pd.DataFrame({'Country':['Bolivia','Bolivia, The Republic of'],'code':[None,None]})
Create Dataframe from dictionary of key-value code 从键值代码字典创建数据框
df_keyval=pd.DataFrame({'CountryCode':{'BOL':['Bolivia','Bolivia, The Republic of']}}).reset_index()
Match the Country and get the corresponding Key: 匹配国家/地区并获取相应的密钥:
for idx,rows in df.iterrows():
if rows['Country'] in df_keyval.CountryCode[0]:
df['code']=df_keyval.index[0]
Output: 输出:
Country code
0 Bolivia BOL
1 Bolivia, The Republic of BOL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.