如何在multindex数据透视表中获取两列的总和
pivot_bad_pod_theft_df=pd.pivot_table(bad_pod_theft_df,index=['DELIVERY_DEPOT'],columns=['Month1','BAD_OPEN_OR_CLOSE_STATUS'],values=['CON_NUMBER'],aggfunc={'CON_NUMBER':len},margins=True,fill_value='')
pivot_bad_pod_theft_df.head()
但是我想在下面的SUM列中单独打开和关闭.pls指导我。
Dec-17 Dec-17 Total
OPEN CLOSE
3 3
4 8 12
12 12
3 21 24
1 9 10
3 4 7
1 10 11
27 67 64
但我得到这样的
Dec-17 Dec-17
OPEN CLOSE
3
4 8
3 21
1 9
3 4
1 10
我希望在SUM列中单独打开和关闭
答案 0 :(得分:0)
似乎你需要:
#sum by first level of MultiIndex
df1 = bad_pod_theft_df.sum(axis=1, level=0)
#create MultiIndex
df1.columns = pd.MultiIndex.from_product([df1.columns, ['SUM']])
print (df1)
Dec-17
SUM
0 6
1 12
2 33
3 10
4 7
5 11
#join together
df2 = pd.concat([bad_pod_theft_df, df1], axis=1)
print(df2)
Dec-17
OPEN CLOSE SUM
0 3 3 6
1 4 8 12
2 12 21 33
3 1 9 10
4 3 4 7
5 1 10 11