【问题标题】:Pandas: Loop Through List And Find Word From List in Column ... Create New Column With Found Word from ListPandas:循环遍历列表并从列中的列表中查找单词...使用从列表中找到的单词创建新列
【发布时间】:2018-12-27 00:54:50
【问题描述】:

我有一个如下所示的列表:

list = ['狗', '猫', 马', '鸟']

我在下面有一个示例数据框。我想让我的代码说:如果 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】:

    您可以尝试使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      相关资源
      最近更新 更多