Search code examples
pythonpandassumappendconditional-statements

Python: Add subtotal row to a dataframe with conditions


I'd like to ask for some rookie help here. I have a pivoted DF with subtotals, and I'd like to append a new subtotal to it that is the sum of some other subtotals. For instance, I'd like to create a new subtotal named "DS", that is the sum of other subtotals like CA-1, INT-1 and INT-2. in the pic below, I attach the aimed result.

Thanks in advance!

Pivoted DF. Painted green aimed result


Solution

  • I've figured it out. Suppose you have the pandas pivot table dataframe, and you would like to add subtotals according to some groupers. Let "PIVOT" be the pd's output, you could add the subtotals and grand total with the following code:

    PIVOT=pd.concat([PIVOT.assign(**{x: '' for x in ['index 1', 'index 2', 'index 3'][i:]}).groupby(list(['index 1', 'index 2', 'index 3'])).sum() for i in range(4)]).sort_index()