df = pd.DataFrame( {
'A': ['d','d','d','f','f','f','g','g','g','h','h','h'],
'B': [5,5,6,7,5,6,6,7,7,6,7,7],
'C': [1,1,1,1,1,1,1,1,1,1,1,1],
'S': [2012,2013,2014,2015,2016,2012,2013,2014,2015,2016,2012,2013]
} );
df = (df.B + df.C).groupby([df.A,df.S]).agg(['sum','size']).
unstack(fill_value=0)
df10 = (df.B * df.C).groupby([df.A,df.S]).agg(['sum','size']).
unstack(fill_value=0)
df20 = (df.B - df.C).groupby([df.A,df.S]).agg(['sum','size']).
unstack(fill_value=0)
我可以为df,df10,df20一次运行以下代码吗?顺便说一句,在实际数据中,我将使用与下面相同的代码运行80个数据帧;
df1 = df.groupby(level=0, axis=1).sum()
new_cols= list(zip(df1.columns.get_level_values(0),['total'] * len(df.columns)))
df1.columns = pd.MultiIndex.from_tuples(new_cols)
df2 = pd.concat([df1,df], axis=1).sort_index(axis=1).sort_index(axis=1, level=1)
df2.columns = ['_'.join((col[0], str(col[1]))) for col in df2.columns]