Pandas - map column from dict values in a list

Viewed 1403

I've got a simple DataFrame and a dictionary like:

import pandas as pd

dict = {'x' : ['a', 'c'], 'y': ['b', 'd']}
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c', 3:'d'}})

  col1
0    a
1    b
2    c
3    d

Now I want to do "reverse-mapping" on the dictionary to have another 'col2', and the DataFrame like this:

  col1 col2
0    a    x
1    b    y
2    c    x
3    d    y

Thank you for help!

1 Answers

You can achieve it by using dictionary comprehension and pandas.Series.map() method. The code is following.

>>> df['col2'] = df.col1.map({item: k for k, v in dict.items() for item in v})
>>> print(df)

  col1 col2
0    a    x
1    b    y
2    c    x
3    d    y
Related