2017-08-24 105 views
0

我有熊猫一个数据帧如下:如何根据多指标指数水平得到子总大熊猫据帧

columns    Year_1 Year_2 
Idx_lvl_0 Idx_lvl_1 
Cons.  Prod_1  156 1541 
      Prod_2  312 2311 
Del.  Prod_1   23  12 
      Prod_2   0  4 

问:我怎样才能大部(Cons_total和Del_total)根据Idx_lvl_0为获得以下。

columns    Year_1 Year_2 
Idx_lvl_0 Idx_lvl_1 
Cons.  Prod_1  156 1541 
      Prod_2  312 2311 
      Cons_total 468 3852 
Del.  Prod_1   23  12 
      Prod_2   0  4 
      Del_total  23  16 

回答

2

这是一种方法。快来看看level=0sum总计在dfs

In [1382]: dfs = df.sum(level=0) 

如果顺序并不重要,只是追加附加索引的结果。

In [1383]: df.append(dfs.assign(Idx_lvl_1=dfs.index.str[:-1] + '_Total') 
         .set_index('Idx_lvl_1', append=True)) 
Out[1383]: 
         Year_1 Year_2 
Idx_lvl_0 Idx_lvl_1 
Cons.  Prod_1   156 1541 
      Prod_2   312 2311 
Del.  Prod_1   23  12 
      Prod_2   0  4 
Cons.  Cons_Total  468 3852 
Del.  Del_Total  23  16 

对于订单,你可以使用sort_index

In [1384]: df.append(dfs.assign(Idx_lvl_1=dfs.index.str[:-1] + '_Total') 
         .set_index('Idx_lvl_1', append=True)).sort_index() 
Out[1384]: 
         Year_1 Year_2 
Idx_lvl_0 Idx_lvl_1 
Cons.  Cons_Total  468 3852 
      Prod_1   156 1541 
      Prod_2   312 2311 
Del.  Del_Total  23  16 
      Prod_1   23  12 
      Prod_2   0  4 

dfs

In [1385]: dfs 
Out[1385]: 
      Year_1 Year_2 
Idx_lvl_0 
Cons.   468 3852 
Del.   23  16