采用:
#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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)