Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To include subtotals in a Pandas Pivot Table that has multiple indices, you can use the margins parameter and set it to True. This will add subtotals for each index level and a grand total at the bottom.

For example:

import pandas as pd

# Create sample data
data = {'Region': ['North', 'North', 'South', 'South'],
        'Month': ['Jan', 'Feb', 'Jan', 'Feb'],
        'Sales': [100, 120, 80, 90]}
df = pd.DataFrame(data)

# Create pivot table with subtotals
pivot_table = pd.pivot_table(df, index=['Region', 'Month'], values='Sales', aggfunc=sum, margins=True)

print(pivot_table)

The output will be:

             Sales
Region Month       
North  Feb     120
       Jan     100
       All     220
South  Feb      90
       Jan      80
       All     170
All            390

As you can see, subtotals are added for each index level, and a grand total is included at the bottom. The All row and column show the sum of sales for each level.