【问题标题】:sum of value occurrence grouped by another column pandas df由另一列 pandas df 分组的值出现的总和
【发布时间】:2020-12-06 22:27:34
【问题描述】:

我需要计算name 列中每个值的出现次数,并按industry 列分组。目标是获得每个行业的每个名称的总和。 我的数据如下所示:

industry            name
Home             Mike
Home             Mike,Angela,Elliot
Fashion          Angela,Elliot
Fashion          Angela,Elliot

想要的输出是:

Home Mike:2 Angela:1 Elliot:1
Fashion Angela:2 Elliot:2

【问题讨论】:

  • df['name'] = df['name'].str.split(','); df.explode('name').groupby(['industry', 'name'], as_index=False).count()
  • @Marat 为什么不将其发布为答案?
  • @sushanth 这太微不足道了(问题和答案)。另外,我不想完全调试它,现在它更像是一个方向
  • @Marat 我同意你的看法,但总的来说是一个很好的答案。

标签: python pandas dataframe


【解决方案1】:

您可以使用collections.Counter 返回一系列字典,如下所示:

from collections import Counter
s = df.name.str.split(',').groupby(df.industry).sum().agg(Counter)

Out[506]:
industry
Fashion               {'Angela': 2, 'Elliot': 2}
Home       {'Mike': 2, 'Angela': 1, 'Elliot': 1}
Name: name, dtype: object

注意:每个单元格都是一个Counter 对象。 Counter 是字典的子类,因此您可以将字典操作作为字典对其应用。

【讨论】:

    【解决方案2】:

    将其从 cmets 中移出,经过调试并证明可以正常工作:

    # count() in the next line won't work without an extra column
    df['name_list'] = df['name'].str.split(',')
    df.explode('name_list').groupby(['industry', 'name_list']).count()
    

    结果:

                        name
    industry name_list      
    Fashion  Angela        2
             Elliot        2
    Home     Angela        1
             Elliot        1
             Mike          2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 2021-06-07
      • 2019-02-12
      • 2021-08-07
      • 2017-02-24
      • 2017-03-25
      • 2020-02-05
      相关资源
      最近更新 更多