【问题标题】:multi level groupby and sum in pandas熊猫中的多级groupby和sum
【发布时间】:2020-10-12 09:06:46
【问题描述】:

我需要在多个列过滤器上过滤数据框,尝试过 groupby,但觉得它仅限于 2 个级别。

df_dic = {'col1': [1, 2, 3, 2, 1], 'year': ['2019', '2019', '2020', '2020', '2019'], 'week': ['37', '38', '1', '2', '37'], 'product': [1, 1, 1, 1, 1], 'se': [1, 0, 0, 0, 1], 'sqe': [0, 1, 0, 0, 1]}

数据框:

   col1  year week  product  se  sqe
      1  2019   37        1   1    0
      2  2019   38        1   0    1
      3  2020    1        1   0    0
      2  2020    2        1   0    0
      1  2019   37        1   1    1

尝试过的迭代:在我最近的尝试中,我能够获得每年的周数,但我希望每周获得 product sum、se sum、sqe sum。

预期结果:

{
 "2019": {
         "37":{
               "Product": 2,
               "SE": 2,
               "SQE":1 
               },
         "38":{
               "Product": 1,
               "SE": 0,
               "SQE":1 
               },
               },
   "2020": 
        {
          "1":{
               "Product": 2,
               "SE": 0,
               "SQE":0 
               }
               }
      }

任何帮助将不胜感激。 顺便说一句:这些产品,se 和 sqe 不能合二为一..

【问题讨论】:

  • 试过 sn-p : df.groupby(['year']).apply(lambda grp: grp.groupby('week')['year'].count().to_dict() ).to_dict()

标签: python pandas pandas-groupby


【解决方案1】:

试试:

df.groupby(by="year").apply(lambda grp: grp.groupby(by="week")[["product","se","sqe"]].sum().to_dict("index")).to_dict()

输出:

{'2019': 
       {'37': {'product': 2, 'se': 2, 'sqe': 1},
        '38': {'product': 1, 'se': 0, 'sqe': 1}},

 '2020': 
       {'1': {'product': 1, 'se': 0, 'sqe': 0},
        '2': {'product': 1, 'se': 0, 'sqe': 0}}}

【讨论】:

  • 感谢@DavideBrex,这解决了我的问题,没有任何改变!再次感谢。
【解决方案2】:

要使用我的解决方案,分组键必须是唯一的,因此从您的数据样本中,我 不得不删除最后一行,因为 year == 2019week == 37 发生得更早。

要获得预期的结果,您可以运行:

df.drop(columns='col1').set_index(['year', 'week']).groupby('year').apply(
    lambda grp: grp.reset_index(level=0, drop=True).to_dict(orient='index')).to_dict()

对于您的数据样本(没有最后一行),我得到了:

{2019: {37: {'product': 1, 'se': 1, 'sqe': 0},
        38: {'product': 1, 'se': 0, 'sqe': 1}},
 2020: { 1: {'product': 1, 'se': 0, 'sqe': 0},
         2: {'product': 1, 'se': 0, 'sqe': 0}}}

可以将此代码扩展为更多级别,但必须指定 您想要的所有分组级别。

【讨论】:

  • 在我的问题场景中,列可以重复。 DavideBrex 解决方案对我有用。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2019-04-12
  • 2019-04-12
  • 2021-06-16
  • 2013-10-24
  • 2013-06-06
相关资源
最近更新 更多