Andreas Kaineder
Andreas Kaineder

Reputation: 19

Python pandas: how to assign value to new column if key is in other column

I have a dataframe and want to check if any part of the string from one column is a key from a given dictionary and if so, assign the value of this key to a new column.

dict = {'Apple': 'Fruit', 'Chicken': 'Meat'}

expected df:

#     String           New Column
# 1   'Red apple'      'Fruit'
# 2   'Fried chicken'  'Meat'

I found this post which is very close to what I need to do but I couldn't find a solution with for using a dictionary: python pandas if column string contains word flag

I hope this makes sense, thanks for any help!

Upvotes: 1

Views: 681

Answers (1)

BENY
BENY

Reputation: 323306

We need to change all key's character to upper case in your dict and your df , then we just apply with checking function

d={x.upper(): y for x,y in d.items()}

df['New']=df.String.str.upper().apply(lambda x : ''.join([v if k in x  else '' for k,v in d.items()]))

df
          String    New
0      Red apple  Fruit
1  Fried chicken   Meat

Upvotes: 2

Related Questions