1

i have a df of country codes:

  cntr
0 CN
1 CH

and I want to map the full name and region I have from a dictionary

cntrmap = {"CN":["China","Asia"],"CH":["Switzerland","Europe"]}

I was hoping in something like this, but doesn't work..

df['name'] = df['cntr'].map(cntrmap)[0]
df['region'] = df['cntr'].map(cntrmap)[1]

do you guys have any suggestion? thanks everyone!

2 Answers 2

1

You can create helper DataFrame by DataFrame.from_dict and DataFrame.join to original DataFrame by default left join:

df = pd.DataFrame({'cntr':['CN','CH']})

cntrmap = {"CN":["China","Asia"],"CH":["Switzerland","Europe"]}

df1 = pd.DataFrame.from_dict(cntrmap, orient='index', columns=['name','region'])

df = df.join(df1, on='cntr')
print (df)
  cntr         name  region
0   CN        China    Asia
1   CH  Switzerland  Europe

Your solution works if create 2 dictionaries for map:

map1 = {k:v[0] for k, v in cntrmap.items()}
map2 = {k:v[1] for k, v in cntrmap.items()}

df['name'] = df['cntr'].map(map1)
df['region'] = df['cntr'].map(map2)
Sign up to request clarification or add additional context in comments.

1 Comment

yes I see.. thank you jezrael! not sure why you cannot map on the internal array, it feels intuitive to me. thanks a lot!
1

It's possible to achieve the same with map:

df.join(pd.DataFrame(df['cntr'].map(m).tolist(), columns=['name', 'region']))

Output:

  cntr         name  region
0   CN        China    Asia
1   CH  Switzerland  Europe

1 Comment

Dont use apply(pd.Series) it is slow. Check this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.