Editor

Add Totals with Margins

Advanced · Write the code · from Pandas Pivot Tables and Cross-Tabulation for Business Analysis

From the lesson: Pandas Pivot Tables and Cross-Tabulation for Business Analysis

If you have ever used a pivot table in Excel or Google Sheets, you already understand the core idea. You take a flat table of raw data and reshape it into a summary that shows one variable along the rows, another along the columns, and computed values (sums, averages, counts) in the cells.

Read the lesson

Create the same pivot table as before, but add margins=True to include row and column totals. The margin label should be the default "All".

Print the pivot table. Make sure to use fill_value=0.

import pandas as pd
df = pd.DataFrame({
'region': ['North', 'North', 'South', 'South', 'North'],
'product': ['A', 'B', 'A', 'B', 'A'],
'revenue': [100, 200, 150, 250, 120]
})
# Create pivot table with margins

More Pandas Pivot Table exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz