How to extract keywords (strings) from a list in a column in a python pandas dataframe?

Viewed 57

I have a list of strings that have spaces in them:

lst = ["apple pie", "chocolate shakes", "orange juice"]

and I have a series:

       Explanation 

a      "apple pie is my favorite dessert" 
b      "I love chocolate. But I love chocolate shakes more." 
c      "she is allergic to orange juice" 

and I'm looking to get something like this:

        Explanation                                         Explanation Extracted

a      "apple pie is my favorite dessert"                           "apple pie"
b      "I love chocolate. But I love chocolate shakes more."      "chocolate shakes"
c      "she is allergic to orange juice"                          "orange juice"
1 Answers

I will recommend you use str.findall, since you may have mutiple match within one sentence

df['Explanation Extracted'] = df['Explanation'].str.findall('|'.join(lst))
df
Out[193]: 
                                         Explanation Explanation Extracted
0                  apple pie is my favorite dessert            [apple pie]
1  I love chocolate. But I love chocolate shakes ...    [chocolate shakes]
2                   she is allergic to orange juice         [orange juice]
Related