pivot pandas中的多索引列和

2024-06-16 10:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获取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='')

支点坏吊舱盗窃_测向头()

但我要像下面的开合和列请分开引导我。在

^{pr2}$

但我越来越像这样了

Dec-17      Dec-17 
OPEN    CLOSE   
         3  
   4    8   

   3    21  
   1    9   
   3    4   
   1    10  

我要把和列中的开合和分开


Tags: numberdfcloseindextableopencondec
1条回答
网友
1楼 · 发布于 2024-06-16 10:35:28

你似乎需要:

#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

相关问题 更多 >