Pandas: Adding a df column based on other column with multiple values map to the same new column value
Build your dict
then do map
d={'dog':'ani','cat':'ani','green':'color','blue':'color'}
df1['col2']=df1.col1.map(d)
df1
col1 col2
0 cat ani
1 cat ani
2 dog ani
3 green color
4 blue color
Since multiple items may belong to a single category I suggest you start with a dictionary mapping category to items:
cat_item = {'animal': ['cat', 'dog'], 'color': ['green', 'blue']}
You'll probably find this easier to maintain. Then reverse your dictionary using a dictionary comprehension, followed by pd.Series.map
:
item_cat = {w: k for k, v in cat_item.items() for w in v}
df1['col2'] = df1['col1'].map(item_cat)
print(df1)
col1 col2
0 cat animal
1 cat animal
2 dog animal
3 green color
4 blue color
You can also use pd.Series.replace
, but this will be generally less efficient.