Home > Enterprise >  map dataframe with dictionary with not exact match
map dataframe with dictionary with not exact match

Time:04-19

I want to match my dataframe against a map but not with exact match

No | Fruit 
1 | Apple
2 | Orange
3 | Blood Orange 
4 | Fuji Apple
5 | Apple Granny
6 | Orange USA

dic = {"Apple" : "Apple Cat", "Orange": "Orange Cat"}

IDEAL OUTPUT 

No | Fruit | Cat
1 | Apple | Apple Cat
2 | Orange | Orange Cat
3 | Blood Orange | Orange Cat
4 | Fuji Apple | Apple Cat
5 | Apple Granny | Apple Cat
6 | Orange USA | Orange Cat

i tried the code below but it requires exact match
df["Cat"] = df["Fruit"].map(dic)

Any help is appreciated! Thank you

CodePudding user response:

You can extract the mapped keys to Cat column then map the dict.

df['Cat'] = df['Fruit'].str.extract('(%s)' % '|'.join(dic.keys()))
df['Cat'] = df['Cat'].map(dic)
print(df)

   No         Fruit         Cat
0   1         Apple   Apple Cat
1   2        Orange  Orange Cat
2   3  Blood Orange  Orange Cat
3   4    Fuji Apple   Apple Cat
4   5  Apple Granny   Apple Cat
5   6    Orange USA  Orange Cat
  • Related