代码之家  ›  专栏  ›  技术社区  ›  PineNuts0

熊猫:遍历列表并在列中从列表中查找单词…使用“从列表中查找单词”创建新列

  •  0
  • PineNuts0  · 技术社区  · 6 年前

    我有一个列表如下:

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

    我有一个样本数据框下面。我希望我的代码说明:如果文本在列表中包含一个单词,则创建一个名为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
    

    我知道一种不有效的方法,可以使用如下语法:如果单词在文本列中,则将该单词放在新列中但我真正的dataframe有一长串单词,上面的方法太繁琐了。

    1 回复  |  直到 6 年前
        1
  •  0
  •   macaw_9227    6 年前

    您可以尝试使用df.apply和set intersection查看文本列和单词列表中同时出现的单词。

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

    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