【问题标题】:Count words in a column of strings in Pandas在 Pandas 中计算一列字符串中的单词
【发布时间】:2018-03-15 03:55:05
【问题描述】:

我有一个 pandas 数据框,其中包含给定时间段的查询和计数,我希望将此数据框转换为唯一词的计数。例如,如果数据框包含以下内容:

query          count
foo bar        10
super          8 
foo            4
super foo bar  2

我希望收到以下数据框。例如单词“foo”在表中出现了 16 次。

word    count
foo     16
bar     12
super   10

我正在使用下面的函数,但这似乎不是执行此操作的最佳方法,它忽略了每行的总数。

def _words(df):
  return Counter(re.findall(r'\w+', ' '.join(df['query'])))

任何帮助将不胜感激。

提前致谢!

【问题讨论】:

    标签: python pandas group-by pandas-groupby


    【解决方案1】:

    选项 1

    df['query'].str.get_dummies(sep=' ').T.dot(df['count'])
    
    bar      12
    foo      16
    super    10
    dtype: int64
    

    选项 2

    df['query'].str.get_dummies(sep=' ').mul(df['count'], axis=0).sum()
    
    bar      12
    foo      16
    super    10
    dtype: int64
    

    选项 3
    numpy.bincount + pd.factorize
    还强调了cytoolz.mapcat 的使用。它返回一个迭代器,在该迭代器中映射一个函数并连接结果。这很酷!

    import pandas as pd, numpy as np, cytoolz
    
    q = df['query'].values
    c = df['count'].values
    
    f, u = pd.factorize(list(cytoolz.mapcat(str.split, q.tolist())))
    l = np.core.defchararray.count(q.astype(str), ' ') + 1
    
    pd.Series(np.bincount(f, c.repeat(l)).astype(int), u)
    
    foo      16
    bar      12
    super    10
    dtype: int64
    

    选项 4
    荒谬地使用东西......只需使用选项1。

    pd.DataFrame(dict(
        query=' '.join(df['query']).split(),
        count=df['count'].repeat(df['query'].str.count(' ') + 1)
    )).groupby('query')['count'].sum()
    
    query
    bar      12
    foo      16
    super    10
    Name: count, dtype: int64
    

    【讨论】:

      【解决方案2】:

      melt + groupby + sum 的另一种选择:

      df['query'].str.split(expand=True).assign(count=df['count'])\
                                .melt('count').groupby('value')['count'].sum()
      
      value
      bar      12
      foo      16
      super    10
      Name: count, dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2021-01-09
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2020-08-08
        相关资源
        最近更新 更多