熊猫:循环列表并从列中的列表中查找单词...使用列表中的找到的单词创建新列

问题描述 投票:0回答:1

我有一个列表如下:

list = ['dog','cat',horse','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列中的单词,则将该单词放在新列中。但我真正的数据框有一个很长的单词列表,上面的方法太繁琐了。

string list pandas find conditional
1个回答
0
投票

您可以尝试使用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
© www.soinside.com 2019 - 2024. All rights reserved.