Reputation: 135
I have a dataframe with a column df['Country']. I have created a dictionary with all of the continents as keys and the values as a list of the corresponding countries.
continents = { "North America" : ["Canada","Mexico","United States"]}
I would like to map this to my dataframe where it creates a column with each value in df['Country'] corresponding continent.
I have tried the below but it returns a column of NA values
df['Continents'] = df['Country'].map(continents)
Do I need to create a function to map the continents or can I use the pandas .map() method?
Upvotes: 2
Views: 1428
Reputation: 260640
You have the wrong format for your dictionary, you need the reverse (and no list).
You can use this to get the right format:
countries_map = {country: continent
for continent,countries in continents.items()
for country in countries}
output:
{'Canada': 'North America',
'Mexico': 'North America',
'United States': 'North America'}
Then proceed as:
df['Continents'] = df['Country'].map(countries_map)
Upvotes: 2