【问题标题】:Pandas Dataframe: count number of IDs based on occurence of words in a text columnPandas Dataframe:根据文本列中单词的出现来计算 ID 的数量
【发布时间】:2015-10-29 06:21:06
【问题描述】:

我有一个这样的熊猫数据框:

id   comment

1    its not proper
2    improvement needed
3    organization is proper
4    registration not done
5    timelines not proper

对于这组单词 ['proper','organization','done'] 我想计算它们出现的 id 数量。所以输出应该是这样的:

proper         3
organization   1
done           1

我已经尝试过使用 for 循环:

word_list = ['proper','organization','done']
final _list = {'proper':0,'organization':0,'done':0}
for index,row in data.iterrows():
    for word in word_list:
        if word in row['comment'].split(' '):
            final_list[word] += 1

有什么方法可以在不使用任何 for 循环的情况下做到这一点...

【问题讨论】:

  • 你根本不想要for loop?
  • @WoodChopper,出于好奇,我对 my answer 进行了计时(没有 for 循环)并将其与 accepted answer 进行了比较。通常情况下,for 循环恰好更快(12 毫秒对 22 毫秒)。教训:不要总是盲目地尝试避免for 循环!
  • get_dummies 会很慢,因为有额外的列。而且时间会成倍增加,没有搜索词可以说我们需要搜索大约 1000 个不同的词

标签: python string pandas dataframe


【解决方案1】:

您可以在words 的列表理解中使用str.contains 并对布尔值求和

In [23]: words = ['proper','organization','done']

In [24]: pd.DataFrame([[wrd, df['comment'].str.contains(wrd).sum()] for wrd in words])
Out[24]:
              0  1
0        proper  3
1  organization  1
2          done  1

【讨论】:

  • 我不认为 .contains() 与 OP 在他的代码中所做的相同, .contains() 也会匹配部分单词。
  • 好吧,我猜 OP 不太关心精确的单词匹配。他正在分裂计数..
  • 我正在寻找完全匹配,我是按空格和匹配分割的。
  • 然后使用正则表达式操作exactmatch = re.compile(r'\b(?:%s)\b' % '|'.join(word_list)) 然后df.comment.map(lambda x: re.findall(exactmatch,x)) 返回单词列表加入列表进行计数。
  • @WoodChopper 与原始解决方案相比,性能会受到怎样的影响?
【解决方案2】:

您可以使用.str 访问器,然后使用.str.split() 函数来拆分comment 中的字符串。使用df['comment'].str.split().values 将为您提供包含单词的数组数组。示例 -

In [35]: df['comment'].str.split().values
Out[35]:
array([['its', 'not', 'proper'], ['improvement', 'needed'],
       ['organization', 'is', 'proper'], ['registration', 'not', 'done'],
       ['timelines', 'not', 'proper']], dtype=object)

然后,您可以使用collections.Counter 来计算您想要的字符串。示例 -

word_set = {'proper','organization','done'}
result = Counter(x for lst in df['comment'].str.split().values
                   for x in lst if x in word_set)

这不会删除for 循环,而是使用生成器表达式,它比传统的for 循环要快一点。

同样使用word_set 会更快,因为在set 中搜索是恒定时间,而在列表中搜索是O(n)。


演示 -

In [34]: df
Out[34]:
   id                 comment
0   1          its not proper
1   2      improvement needed
2   3  organization is proper
3   4   registration not done
4   5    timelines not proper

In [35]: df['comment'].str.split().values
Out[35]:
array([['its', 'not', 'proper'], ['improvement', 'needed'],
       ['organization', 'is', 'proper'], ['registration', 'not', 'done'],
       ['timelines', 'not', 'proper']], dtype=object)

In [36]: word_set = {'proper','organization','done'}

In [37]: result = Counter(x for lst in df['comment'].str.split().values
   ....:                    for x in lst if x in word_set)

In [38]: result
Out[38]: Counter({'proper': 3, 'done': 1, 'organization': 1})

【讨论】:

    【解决方案3】:
    In [105]:
    words = ['proper','organization','done']
    for word in words:
        df[word] = df.comment.str.contains('\\b' + word + '\\b' , case = True , regex = True)
    
    Out[105]:
    comment                         proper  organization    done
    its not proper                   True   False          False
    improvement needed               False  False          False
    organization is proper           True   True           False
    registration not done            False  False          True
    timelines not proper             True   False          False
    
    In [103]:    
    df.iloc[: , 1:].sum()
    Out[103]:
    proper          3
    organization    1
    done            1
    dtype: int64
    

    【讨论】:

      【解决方案4】:

      编辑:get_dummies 也可以在没有任何for 循环的情况下完成:

      df['comment'].str.get_dummies(' ').sum()[['proper','organization','done']]
      
      Out[151]: 
      proper          3
      organization    1
      done            1
      

      注意:求和后的过滤可以巧妙地处理缺失的单词。


      原始答案:显然到目前为止所有答案都使用for 循环。避免它的一种方法是使用pd.value_counts:

      df['comment'].str.split().apply(pd.value_counts)[['proper','organization','done']]
      
      Out[149]: 
         proper  organization  done
      0       1           NaN   NaN
      1     NaN           NaN   NaN
      2       1             1   NaN
      3     NaN           NaN     1
      4       1           NaN   NaN
      

      您所要做的就是对结果数据框求和:

      _.sum()
      
      Out[150]: 
      proper          3
      organization    1
      done            1
      

      如果列表中的某个单词不在文本中的任何位置,您只需要调整代码。


      【讨论】:

        【解决方案5】:

        您可以在 pandas 中使用.str.contains() 方法:

        import pandas as pd
        
        cols = ['id', 'comment']
        data = [[1, 'its not proper'],
                [2, 'improvement needed'],
                [3, 'organization is proper'],
                [4, 'registration not done'],
                [5, 'timelines not proper']]
        df = pd.DataFrame(data, columns=cols)
        word_list = ['proper','organization','done']
        row_counts = {word: df[df.comment.str.contains(word)].shape[0]
                      for word in word_list}
        print row_counts
        # output is:
        # {'proper': 3, 'organization': 1, 'done': 1}
        

        【讨论】:

        • 我不认为 .contains() 与 OP 在他的代码中所做的相同, .contains() 也会匹配部分单词。
        猜你喜欢
        • 1970-01-01
        • 2014-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-19
        相关资源
        最近更新 更多