Pandas:遍历列表并从列表中的列中查找单词...使用从列表中找到的单词创建新列

Pandas: Loop Through List And Find Word From List in Column ... Create New Column With Found Word from List

我有如下所示的列表:

list = ['dog', 'cat', 马', 'bird']

下面有一个示例数据框。我想让我的代码说:如果 TEXT 在您的列表中包含一个词,那么创建一个名为 EXTRACT 的新列,该列挑选出关键词并将它们放入新列中。

ID  TEXT               
1   hello you person    
2   you have a dog     
3   the bird flew      
4   the horse is here  
5   bird bird bird     

下面是我想要的数据框:

ID  TEXT               EXTRACT
1   hello you person    
2   you have a dog     dog
3   the bird flew      bird
4   the horse is here  horse
5   bird bird bird     bird

我知道使用如下语法执行此操作的效率不高的方法:如果单词在 TEXT 列中,则将该单词放入新列中。但是我的真实数据框有很长的单词列表,上面的方法太繁琐了。

您可以尝试使用 df.apply 并设置交集以查看哪些单词同时出现在文本列和单词列表中。

您需要考虑当文本栏中出现多个单词时会发生什么情况

def word_finder(x):
  df_words = set(x.split(' '))
  extract_words =  word_set.intersection(df_words)
  return ', '.join(extract_words)

df = pd.DataFrame(data = {'text' : ['hello you person', 'you have a dog', 'the bird flew', 'the horse is here', 'bird bird bird', 'dog and cat']})

word_set = {'dog', 'cat', 'horse', 'bird'}

df['extract'] = df.text.apply(word_finder)

输出

                text   extract
0   hello you person          
1     you have a dog       dog
2      the bird flew      bird
3  the horse is here     horse
4     bird bird bird      bird
5        dog and cat  dog, cat