I want to search for a set of values in a particular column. If a match occurs, return the matching string. Currently I only get a true or false back. Here are the steps:
- Create df:
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4', np.nan],
'Price': [22000,25000,27000,35000, 29000],
'Liscence Plate': ['ABC 123', 'XYZ 789', 'CBA 321', 'ZYX 987', 'DEF 456']}
df = pd.DataFrame(Cars,columns= ['Brand', 'Price', 'Liscence Plate'])
- Search for particular set of values:
search_for_these_values = ['Honda', 'Toy', 'Ford Focus', 'Audi A4 2019']
pattern = '|'.join(search_for_these_values)
df['Match'] = df["Brand"].str.contains(pattern, na=False)
- Print df:
print(df)
Brand Price Liscence Plate Match
0 Honda Civic 22000 ABC 123 True
1 Toyota Corolla 25000 XYZ 789 True
2 Ford Focus 27000 CBA 321 True
3 Audi A4 35000 ZYX 987 False
4 NaN 29000 DEF 456 False
I would like to have the following for column Match:
Brand Price Liscence Plate Match
0 Honda Civic 22000 ABC 123 Honda
1 Toyota Corolla 25000 XYZ 789 Toy
2 Ford Focus 27000 CBA 321 Ford Focus
3 Audi A4 35000 ZYX 987
4 NaN 29000 DEF 456