Search text in column A for dict key, if found then set column B to dict value in Pandas dataframe

Question:

Given a dataframe and a dict like the following:

Col A             Col B  
f3s34Roger         nan  
bll23Dawn          nan  
Misty3r2w          nan  
efJunea4l          nan  

vendor_dict = {'Roger': 'cups','Charlie':'plates','Misty':'bowls'}

I want to search each row to see if Col ‘A’ contains a key in the dict. If it does, I want to set Col ‘B’ to be the key’s value.

Testing with just a static value, this works:

df['Col B'] = np.where(df['Col A'].str.find('Roger'),'', 'cups')

But that doesn’t give me the dict mapping. I’ve tried:

df['Col B'] = np.where(df['Col A'].str.find().map(vendors)

but that’s not correct. Any ideas?

Asked By: kimander

||

Answers:

Use str.findall then use map

df['Col B']=df['Col A'].str.findall('|'.join(vendor_dict.keys())).str[0].map(vendor_dict)
0     cups
1      NaN
2    bowls
3      NaN
Name: ColA, dtype: object
Answered By: BENY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.