How to add a column with string values of a dictionary in Python dataframe

Viewed 379

I am trying to add a column with values from a dictionary.

The DataFrame looks as follows with a total of 29 countries dataframe screenshot

My Dictionary looks as follows:

# Define a dictionary containing european Regions 
eu_regions = {'Central and Eastern Europe': ['Latvia', 'Bulgaria', 'Lithuania', 'Croatia', 'Czechia','Poland','Romania', 'Slovakia', 'Slovenia', 'Hungary'],
        'Northern Europe': ['Sweden', 'Norway', 'Denmark', 'Finland', 'Estonia'],
        'Western Europe': ['Austria', 'Belgium', 'Luxembourg', 'Netherlands', 'France', 'Germany', 'Ireland', 'Norway', 'United Kingdom'],
        'Southern Europe': ['Italy', 'Cyprus','Malta', 'Portugal', 'Greece', 'Spain']}

To add the new columns called "region", which is meant to add the region of each country I used following command.

eu_vaccine_df['region'] = eu_vaccine_df['country'].map(eu_regions)

eu_vaccine_df.head()

In the result however, the new column "region" is created but does not add the new country and fails to match the country to the region of the dictionary.

1 Answers

Does this help?

country_dct = {}
for key, countries in eu_regions.items():
    
    for country in countries:
        country_dct[country] = key


eu_vaccine_df['region'] = eu_vaccine_df['country'].map(country_dct)

eu_vaccine_df.head()
Related