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?
IIUC 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.