abhinav
abhinav

Reputation: 1138

How to get sub total according to index level in multi-index pandas dataframe

I have a dataframe in pandas as following:

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

Question: How can i get subtotal(Cons_total and Del_total) according to Idx_lvl_0 as following.

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

Upvotes: 3

Views: 1160

Answers (1)

Zero
Zero

Reputation: 76927

Here's one way. Take sum totals at level=0 in dfs

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

If order isn't important, just append the result of appended index.

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

For order, you can use 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 is

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

Upvotes: 4

Related Questions