We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Pivot Tables

A pivot table reshapes data from long format (many rows, few columns) to wide format (fewer rows, more columns). Think of it as a groupby that spreads one column's values into new columns.

Pivot tables are often exactly what you want in a report or dashboard – they map 1:1 to what stakeholders expect to see.

Long vs. Wide Format

In long format, every observation is a row:

team priority response_minutes
Support high 45
Support low 12
Billing high 60
Billing low 20

In wide format, categories become columns:

team high low
Support 45 12
Billing 60 20

Creating a Pivot Table

Use pd.pivot_table():

tickets = pd.DataFrame(
    {
        "team": ["Support", "Support", "Billing", "Billing", "Support", "Billing"],
        "priority": ["high", "low", "high", "low", "high", "low"],
        "response_minutes": [45, 12, 60, 20, 30, 25],
    }
)

pivot = pd.pivot_table(
    tickets,
    values="response_minutes",
    index="team",
    columns="priority",
    aggfunc="mean",
)

Pivot for presentation, but keep long format for computation. Long format is usually easier to work with for further analysis.

Handling Missing Combinations

If some group combinations don't exist, you'll get NaN. Use fill_value to replace missing combinations:

pivot = pd.pivot_table(
    tickets,
    values="response_minutes",
    index="team",
    columns="priority",
    aggfunc="mean",
    fill_value=0,
)

Assignment

SnackStack's operations team wants an energy dashboard: total power draw for every region, broken out by device type.

Complete the energy_grid_by_region_and_type function. It accepts a df of telemetry rows with region, device_type, and energy_kwh columns, and returns a pivot table.