在熊猫中如何从一列中的句子中提取特定单词

时间:2018-10-29 09:49:27

标签: python pandas

我有df1,我想从'desc'中的句子中提取'flavor',然后得到df2。我有一个口味列表,我根据该列表决定选择哪个口味。如何在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

1 个答案:

答案 0 :(得分:1)

如果要按列表使用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

如果可能,多个flavours使用str.findall进行列表,然后使用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