Reputation: 1424
I am trying to map values to dataframe columns from a dictionary. Here is the code:
#
import pandas as pd
region_dict = {'Russia':['Europe','Eastern Europe'],
'South Korea':['Asia','Easter Asia'],
'Iran':['Asia','Southern Asia'],
'North Korea':['Asia','Eastern Asia']}
region_dict
#> {'Russia': ['Europe', 'Eastern Europe'],
'South Korea': ['Asia', 'Eastern Asia'],
'Iran': ['Asia', 'Southern Asia'],
'North Korea': ['Asia', 'Eastern Asia']}
df = pd.DataFrame({'Country':['Russia', 'Iran', 'South Korea','USA'],
'continent':['NaN','NaN','NaN','Americas'],
'sub_region':['NaN','NaN','NaN','Northern America']})
df
#> Country continent sub_region
0 Russia NaN NaN
1 Iran NaN NaN
2 South Korea NaN NaN
3 USA Americas Northern America
Desired Output:
#> Country Continent Sub_region
0 Russia Europe Eastern Europe
1 Iran Asia Southern Asia
2 South Korea Asia Eastern Asia
3 USA NaN NaN
I tried
df[['continent','sub_region']] = df['country'].map(region_dict)
***Error***
ValueError: shape mismatch: value array of shape (20036,) could not be broadcast to indexing result of shape (2,20036)
This way works when the dictionary is in the form
region_dict = {'Russia':'Asia'}
and I map as
df['continent'] = df['country'].map(region_dict)
Questions
region_dict['Russia'][1]
to the df column, how shall I do it?Upvotes: 0
Views: 91
Reputation: 75080
You should convert the mapped series of lists to a df and then assign:
df[['continent','sub_region']] = pd.DataFrame(df['Country'].map(region_dict).tolist())
Upvotes: 1