Editor

Create a Sales Pivot Table

Intermediate · 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 a pivot table from df with region as the index, product as the columns, and revenue as the values. Use sum as the aggregation function and fill_value=0.

Print the resulting pivot table.

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 the pivot table

More Pandas Pivot Table exercises

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