'How to add a Grand Total of several functions multindex dataframe?

I would like to create a line that calculates the functions for all the groups :

I am using the following code :

def notional_and_margin(df,dico):
''' Takes a dataframe as input'''

pivot_notional = df.groupby("Groups").apply(lambda sub: sub.pivot_table(
    values=["Amount", "Margin", "count"],
    index=["Quarter"],
    aggfunc=[np.sum, np.mean, np.median, max], margins=True, margins_name="Total Group"))

pivot_notional.drop([("mean", "count"), ("median", "count"),("max","count")], inplace=True, axis=1)

I am trying to add a line to calculate each function (sum, mean, median, max) to the all the data that are in another dataframe. I tried to calculate this values separately and add a line, but that's not really "clean" in terms of coding.

Do you have any idea ? Thank you [1]: https://i.stack.imgur.com/QEJSE.jpg



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source