Python-groupby上的Pandas小计

Python-groupby上的Pandas小计,第1张

Python-groupby上的Pandas小计

采用

#if necessary convert TYPE column to stringdf['TYPE'] = df['TYPE'].astype(str)df = df.groupby(["SCENARIO", "STATUS", "TYPE"])['TYPE'].count()#aggregate sum by first 2 levelsdf1 = df.groupby(["SCENARIO", "STATUS"]).sum()#add 3 level of MultiIndex df1.index = [df1.index.get_level_values(0), df1.index.get_level_values(1), ['Total'] * len(df1)]#thanks MaxU for improving#df1 = df1.set_index(np.array(['Total'] * len(df1)), append=True)print (df1)SCENARIO  STATUS       AAA       51      Total    3          53      Total    1BBB       51      Total    1CCC       51      Total    1Name: TYPE, dtype: int64

#join together and sortsdf = pd.concat([df, df1]).sort_index(level=[0,1])print (df)SCENARIO  STATUS  TYPE AAA       51      1        2       9        1       Total    3          53      228      1       Total    1BBB       51      43       1       Total    1CCC       51      187      1       Total    1Name: TYPE, dtype: int64


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5655072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存