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 Table Aggregations

A pivot table can calculate more than one summary at a time, which is useful when a report needs multiple views of the same data, like:

  • Average response time by support team and priority
  • Maximum response time by support team and priority

Pass a list of functions to aggfunc:

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],
    }
)

# Calculate both mean and max
pivot = pd.pivot_table(
    tickets,
    values="response_minutes",
    index="team",
    columns="priority",
    aggfunc=["mean", "max"],
)
print(pivot)
#             mean        max
# priority    high   low high low
# team
# Billing     60.0  22.5   60  25
# Support     37.5  12.0   45  12

The result has a set of columns for each aggregation function. Read it in two layers:

  1. The top column level is the aggregation function, mean or max.
  2. The second column level is the pivoted value, high or low.

So mean -> high means average response time for high-priority tickets, while max -> high means the slowest high-priority response time.

When to Use Multiple Aggregations

Multiple pivot aggregations are useful for compact report tables, since they let you compare related metrics without building several separate pivots. But they can create awkward column labels.

If you need clean column names for more analysis, a named groupby().agg() is often easier to work with.

Assignment

SnackStack's operations team wants one compact energy report: for every region, both the total and average power draw of each device type, side by side.

Complete the energy_summary_by_region_and_type function. It accepts a DataFrame with region, device_type, and energy_kwh columns and returns a pivot table.