TExcelTAD
Home › Data Science › DS Grouping & Aggregation

DS Grouping & Aggregation

Many questions are really comparisons between groups: Are Saturdays busier than Mondays? How much do wet days lose? Which temperature range is best? The pandas tool for all of them is split–apply–combine:

  1. Split the rows into groups by one or more keys.
  2. Apply a summary (mean, count, …) to each group.
  3. Combine the results into a new table.

In pandas this is one expression: df.groupby(keys)[column].agg(functions).

Grouping by day of the week

Our dataset has a date column, from which pandas can derive the weekday name with .dt.day_name():

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["weekday"] = bikes["date"].dt.day_name()
order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

by_day = bikes.groupby("weekday")["rides"].agg(["count", "mean", "min", "max"])
print(by_day.reindex(order).round(1))
           count   mean  min  max
weekday
Monday         9  329.6  167  470
Tuesday        9  302.0  186  475
Wednesday      9  308.4  124  446
Thursday       9  347.9  186  496
Friday         8  351.9  204  527
Saturday       8  404.4  220  523
Sunday         8  460.6  307  572

Groups come back sorted alphabetically, so reindex(order) puts the weekdays in calendar order. Saturday and Sunday stand out, as expected.

Several aggregations, several columns

agg accepts a dictionary or named aggregations — keyword arguments of the form new_name=(column, function) — which give tidy column names:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["wet"] = np.where(bikes["rain_mm"] > 0, "wet", "dry")
summary = bikes.groupby("wet").agg(
    days=("rides", "size"),
    avg_rides=("rides", "mean"),
    avg_temp=("temp_c", "mean"),
    total_rides=("rides", "sum"),
)
print(summary.round(1))
diff = summary.loc["dry", "avg_rides"] - summary.loc["wet", "avg_rides"]
print(f"\nDry days average {diff:.0f} more rides than wet days.")
     days  avg_rides  avg_temp  total_rides
wet
dry    42      382.7      18.1        16075
wet    18      291.7      16.1         5251

Dry days average 91 more rides than wet days.

Notice the avg_temp column: wet days were only about 2 °C cooler — worth roughly 25 rides at 12.5 rides per degree, far less than the 91-ride gap. So the gap isn't simply "wet days were colder". Checking such side-by-side columns is a quick guard against confounding.

Binning a numeric variable

To group by a numeric variable, first cut it into bins with pd.cut:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["temp_band"] = pd.cut(bikes["temp_c"], bins=[0, 10, 15, 20, 25, 30],
                            labels=["<10", "10-15", "15-20", "20-25", "25-30"])
print(bikes.groupby("temp_band", observed=True)["rides"].agg(["count", "mean"]).round(0))
           count   mean
temp_band
<10           15  230.0
10-15          7  306.0
15-20         10  326.0
20-25         18  427.0
25-30         10  478.0

Rides climb from band to band: from 230 below 10 °C to 478 above 25 °C, roughly 250 more rides across about 20 degrees — consistent with the regression slope of about 12.5 rides per degree. The steps between neighbouring bands are uneven because some bands hold only 7–10 days.

Two keys: a pivot table

Grouping by two keys and spreading one of them across columns gives a pivot table — the same thing spreadsheet users know:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["day_type"] = np.where(bikes["weekend"] == 1, "weekend", "weekday")
bikes["wet"] = np.where(bikes["rain_mm"] > 0, "wet", "dry")

table = bikes.pivot_table(index="day_type", columns="wet", values="rides",
                          aggfunc="mean", margins=True, margins_name="all")
print(table.round(0))
print()
print(pd.crosstab(bikes["day_type"], bikes["wet"]))
wet         dry    wet    all
day_type
weekday   356.0  266.0  327.0
weekend   449.0  383.0  432.0
all       383.0  292.0  355.0

wet       dry  wet
day_type
weekday    30   14
weekend    12    4

pivot_table shows mean rides for each combination, with margins=True adding overall rows and columns. pd.crosstab counts how many days fall in each cell — always check the counts, because a mean based on 4 days is much less reliable than one based on 30.

transform: group values back on each row

Sometimes you want a group statistic next to every row, for example to compare each day with the average for its weekday type. transform returns a result with the original length:

python · try it yourself
import pandas as pd

days = pd.DataFrame({
    "day_type": ["weekday", "weekday", "weekend", "weekday", "weekend"],
    "rides": [298, 439, 523, 405, 497],
})
days["type_mean"] = days.groupby("day_type")["rides"].transform("mean")
days["vs_type"] = days["rides"] - days["type_mean"]
print(days.round(1))
  day_type  rides  type_mean  vs_type
0  weekday    298      380.7    -82.7
1  weekday    439      380.7     58.3
2  weekend    523      510.0     13.0
3  weekday    405      380.7     24.3
4  weekend    497      510.0    -13.0

Test yourself

What are the three steps behind groupby?

  1. Load, clean, plot
  2. Split, apply, combine
  3. Sort, filter, join
  4. Fit, predict, evaluate

Which function cuts a numeric column into ranges for grouping?

  1. pd.split
  2. pd.cut
  3. pd.bin
  4. df.groupby(range)

What does groupby(...).transform("mean") return?

  1. One row per group
  2. A value for every original row: its group's mean
  3. A pivot table
  4. Only the largest group