import pandas as pd sales = pd.DataFrame( { "region": ["East", "East", "East", "West", "West", "West", "North", "North"], "quarter": ["Q1", "Q1", "Q2", "Q1", "Q2", "Q2", "Q1", "Q3"], "category": [ "hardware", "software", "hardware", "hardware", "hardware", "software", "software", "hardware", ], "revenue": [1200, 800, 950, 1400, 1100, 650, 500, 700], } ) pivot = pd.pivot_table( sales, values="revenue", index="region", columns="quarter", aggfunc="sum", fill_value=0, margins=True, margins_name="Total", ) print(pivot.to_string()) print() print("West Q2 revenue:", pivot.loc["West", "Q2"]) print("grand total:", pivot.loc["Total", "Total"]) expected = ( sales.groupby(["region", "quarter"])["revenue"] .sum() .unstack(fill_value=0) ) assert pivot.loc["West", "Q2"] == expected.loc["West", "Q2"] assert pivot.loc["Total", "Total"] == sales["revenue"].sum() print("verification: pivot totals match grouped source data")