【问题标题】:Add grand total and subtotal for Pandas pivot table为 Pandas 数据透视表添加总计和小计
【发布时间】:2019-04-07 00:31:23
【问题描述】:
df=pd.DataFrame({'Region':['Oceanian','Europe','Asia','America','Europe','America','Asia','Oceanian','America'],'Country':["AU","GB","KR","US","GB","US","KR","AU","US"],'Region Manager':['TL','JS','HN','AL','JS','AL','HN','TL','AL'],'Campaign Stage':['Start','Develop','Develop','Launch','Launch','Start','Start','Launch','Develop'],'Product':['abc','bcd','efg','lkj','fsd','opi','vcx','gtp','qwe'],'Curr_Sales': [453,562,236,636,893,542,125,561,371],'Curr_Revenue':[4530,7668,5975,3568,2349,6776,3046,1111,4852],'Prior_Sales': [235,789,132,220,569,521,131,777,898],'Prior_Revenue':[1530,2668,3975,5668,6349,7776,8046,2111,9852]})
table=pd.pivot_table(df, values=['Curr_Sales', 'Curr_Revenue', 'Prior_Sales', 'Prior_Revenue'], index=['Region','Country', 'Region Manager','Campaign Stage','Product'],aggfunc='sum')

如何向每个“区域”添加小计并在底部添加总计?

感谢任何想法!谢谢。

【问题讨论】:

  • 我觉得这和你之前的问题差不多
  • 此代码无效。它将所有行组合在一起

标签: python pandas pivot-table multi-index subtotal


【解决方案1】:

与您之前的问题非常相似的解决方案,但是您可以为缺少的级别插入空白字符串(受@piRSquared here 启发):

out = pd.concat([d.append(d.sum().rename((k, '', '', '', 'Subtotal'))) for k, d in table.groupby('Region')]).append(table.sum().rename(('Grand', '', '', '', 'Total')))

out.index = pd.MultiIndex.from_tuples(out.index)

产量:

                                 Curr_Revenue     ...       Prior_Sales
America  US AL Develop qwe               4852     ...               898
               Launch  lkj               3568     ...               220
               Start   opi               6776     ...               521
                       Subtotal         15196     ...              1639
Asia     KR HN Develop efg               5975     ...               132
               Start   vcx               3046     ...               131
                       Subtotal          9021     ...               263
Europe   GB JS Develop bcd               7668     ...               789
               Launch  fsd               2349     ...               569
                       Subtotal         10017     ...              1358
Oceanian AU TL Launch  gtp               1111     ...               777
               Start   abc               4530     ...               235
                       Subtotal          5641     ...              1012
Grand                  Total            39875     ...              4272

【讨论】:

  • 实际上,@piRSquared 的答案适用于三个索引。但是这个 df 有五个索引,这是行不通的。
  • 以上内容有什么问题? “不工作”无法明确您的问题。
  • @Boomshakalaka 3 和 5 甚至 100 ,这里的逻辑都是一样的
  • 嗨@rahlf23,新代码回答了我的问题,感谢您的帮助。谢谢
猜你喜欢
  • 2019-04-15
  • 2021-11-03
  • 1970-01-01
  • 2013-03-12
  • 2012-11-29
  • 2017-05-13
  • 2016-10-24
  • 1970-01-01
相关资源
最近更新 更多