Reputation: 43
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?
The desired output is
> Country Code
> 'Bolivia' 'BOL'
> 'Bolivia, The Republic of' 'BOL'
Thanks for your help!
Upvotes: 0
Views: 47
Reputation: 1824
Using .apply()
df["Code"] = df.Country.apply(lambda x: ''.join(i for i, j in CountryCode.items() if x in j))
Output:
Country Code
0 Bolivia BOL
1 Bolivia, The Republic of BOL
Upvotes: 1
Reputation: 13255
Create reverse dictionary of CountryCode
and map
it with Country
column:
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'}
Upvotes: 1
Reputation: 4638
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
Upvotes: 0