Previously, I have matched values on a different list (this thread How to get a python lookup to return another column after match)
import pandas as pd
import numpy as np
df = pd.DataFrame({'Name':['a cat dog - multiple', 'grey puppy - narrow term', 'a cat puppy', 'reddog - single no spaces', 'acatdog - multiple no spaces']})
df2 = pd.DataFrame({'BroadTerm':['cat', 'cat', 'dog', 'dog'], 'NarrowTerm':['cat', 'kitten', 'puppy', 'dog']})
There are a couple of issues:
- Matching values where there are 1 or more values in a cell (eg row 1 of dataframe)
- Matching values that don't contain any spaces (eg rows 4 and 5 of df)
The base code is
df['Animal'] = df['Name'].str.extract(pat = f"({'|'.join(df2.NarrowTerm)})")[0].map(dict(df2.iloc[:,::-1].values))
But that only works for single hit cells / returns the first hit)
How do I modify the code to do this?