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

Grouping in Pandas

groupby() is the built-in way to aggregate in Pandas. It uses the split-apply-combine pattern.

orders = pd.DataFrame(
    {
        "region": ["West", "East", "West", "East", "West"],
        "revenue": [100, 200, 150, 300, 250],
    }
)

revenue_by_region = orders.groupby("region")["revenue"].sum()

The result:

region
East    500
West    500

Here's what happened:

  1. Split – Pandas grouped the rows by region (West rows together, East rows together)
  2. Apply.sum() ran on each group's revenue column
  3. Combine – Pandas returned the results as a single Series, with the group keys (region) as its index

You can run other aggregation functions as well, once you've grouped the data:

orders.groupby("region")["revenue"].mean()  # average
orders.groupby("region")["revenue"].count()  # number of non-null values
orders.groupby("region")["revenue"].min()  # smallest value
orders.groupby("region")["revenue"].max()  # largest value

Assignment

SnackStack wants a dashboard tile showing how hot each region's devices are running on average.

Complete the average_temperature_by_region function. It accepts a DataFrame with a temperature_celsius column, and returns a tidy DataFrame with one row per region.