Replace or map values in a pandas dataframe column with a one to many dictionary

Viewed 1136

I have a dataframe column which I need to replace with categories defined in a dictionary.

I'm using a dictionary and using a for loop, under which there are if and elif statements with which I replace the values.

   dict_col = {'Red':['Light_Red','Crimson','Ferrari_Red'],'Blue:['Light_Blue','Azure_Blue','Sky_Color']}

I wanted to know if there is a clean and better way to do this rather than using a for loop.

enter image description here

3 Answers

Yes there is. You can use the map function in pandas: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html

You want the dictionary to be the other way around though:

Full example:

import pandas as pd

dict_col = {'Red':['Light_Red','Crimson','Ferrari_Red'],'Blue':['Light_Blue','Azure_Blue','Sky_Color']}
dict_col = {val: k for k, l in dict_col.items() for val in l}
df = pd.DataFrame(("Light_Red", 'Light_Blue'), columns=["Colors"])
df["Colors"].map(dict_col)

Use dict comprehension with swap keys and values first and then pass to Series.map:

df = pd.DataFrame({'Color':['Light_Red','Crimson','Ferrari_Red',
                           'Light_Blue','Azure_Blue','Sky_Color']})
print (df)
         Color
0    Light_Red
1      Crimson
2  Ferrari_Red
3   Light_Blue
4   Azure_Blue
5    Sky_Color

dict_col = {'Red':['Light_Red','Crimson','Ferrari_Red'],
           'Blue':['Light_Blue','Azure_Blue','Sky_Color']}
            
d = {k: oldk for oldk, oldv in dict_col.items() for k in oldv}

print (d)
{'Light_Red': 'Red', 'Crimson': 'Red', 'Ferrari_Red': 'Red', 
 'Light_Blue': 'Blue', 'Azure_Blue': 'Blue', 'Sky_Color': 'Blue'}

df['Color'] = df['Color'].map(d)
print (df)
0   Red
1   Red
2   Red
3  Blue
4  Blue
5  Blue

It would be a bit simpler, when changing structure of the dictionary:

df = pd.DataFrame({
    'Color': ['Light_Red', 'Crimson', 'Ferrari_Red', 'Light_Blue', 'Azure_Blue', 'Sky_Color']
})

dict_col = {
    'Light_Red' : 'Red','Crimson': 'Red','Ferrari_Red': 'Red',
    'Light_Blue': 'Blue','Azure_Blue': 'Blue','Sky_Color': 'Blue'
}

df['Color'] = df['Color'].apply(lambda x: dict_col[x])

df.head()
Related