Chloe
Chloe

Reputation: 217

in pandas how to extract specific words from a sentence in a column

I have df1, and I want to extract 'flavor' from the sentence in 'desc', and get df2. There is a flavor list that I decide which to pick according to the list. How can I get the result in python?

df1:
desc                                flavor
Coke 600mL and Chips                
Coke Zero 600mL and Chips           
390ml Coke + Small Fries            
600ml Coke + Regular Fries with     
Vanilla Coke 600mL and Chips        
Garlic Bread and pepsi 1.25ltr

df2:
 desc                               flavor
 Coke 600mL and Chips               Coke 
 Coke Zero 600mL and Chips          Coke Zero
 390ml Coke + SmallFries            Coke 
 600ml coke + Regular Fries with    Coke 
 Vanilla Coke 600mL and Chips       Vanilla Coke 
 Garlic Bread and pepsi 1.25ltr     Pepsi

> Flavor list: 
Coke 
Coke Zero 
Vanilla Coke 
Pepsi

Upvotes: 0

Views: 3157

Answers (1)

jezrael
jezrael

Reputation: 862681

Use if want extract only one value by list use str.extract:

import re

L = ['Coke Zero', 'Vanilla Coke','Pepsi','Coke']
pat = '|'.join(r"\b{}\b".format(x) for x in L)

df['flavor'] = df['desc'].str.extract('('+ pat + ')', expand=False, flags=re.I)
print (df)
                              desc        flavor
0             Coke 600mL and Chips          Coke
1        Coke Zero 600mL and Chips     Coke Zero
2         390ml Coke + Small Fries          Coke
3  600ml Coke + Regular Fries with          Coke
4     Vanilla Coke 600mL and Chips  Vanilla Coke
5   Garlic Bread and pepsi 1.25ltr         pepsi

If possible multiple flavours use str.findall for lists and then str.join:

df['flavor'] = df['desc'].str.findall(pat, flags=re.I).str.join(' ')

print (df)
                              desc        flavor
0             Coke 600mL and Chips          Coke
1        Coke Zero 600mL and Chips     Coke Zero
2         390ml Coke + Small Fries          Coke
3  600ml Coke + Regular Fries with          Coke
4     Vanilla Coke 600mL and Chips  Vanilla Coke
5   Garlic Bread and pepsi 1.25ltr         pepsi

Upvotes: 4

Related Questions