Skip to content

Aggregation and window functions

Summarize to one row per group, add a group's statistic to every row, and compute running values without using the future.

Applied ~10 min7 steps

You will be able to

  • Choose between summarizing rows and adding a group statistic
  • Write a window function in SQL
  • Avoid a future leak in a rolling statistic

Read first

01

Fewer rows, or more columns?

Read

You have orders and want each customer's average.

  • Group and summarize returns one row per customer. Use it when the customer is your new unit.
  • Group statistic keeps every order and adds the customer's average to each row. Use it to compare an order with its customer's usual.

Both are steps in Prepare (⌘3). The first changes what a row means, so check that your analysis still means what you intended.

02

The mean of means

Predict

Predict first

Group A has 90 people averaging 50. Group B has 10 people averaging 90. What is the overall mean across all 100 people?

Make your guess between 0 and 100 points, then reveal.

Reveal
90×50+10×90100=54\frac{90 \times 50 + 10 \times 90}{100} = 54

Averaging the two group means gives 70, which weights a person in B nine times as much as a person in A. Keep the counts when you aggregate.

03

Windows

In the app

A window functionWindow functionComputes across a set of related rows while keeping every row, whereas GROUP BY collapses them. computes across related rows and keeps them all. Try this in SQL (⌘4), with your own table and columns:

SELECT
  customer_id,
  order_date,
  total,
  AVG(total) OVER (PARTITION BY customer_id) AS customer_avg,
  SUM(total) OVER (
    PARTITION BY customer_id ORDER BY order_date
  ) AS running_total
FROM orders;

PARTITION BY chooses the group, and ORDER BY makes it cumulative. The SQL walkthrough starts with the plain grouped version: the average {{value}} for each {{group}}.

04

Rolling without the future

Reflect

Rolling statistic computes over a moving window of rows, and has an option for past rows only.

A centered seven-day average of sales is fine for describing history. As a feature in a forecast, it hands the model tomorrow's sales, and the model then looks better on paper than it can ever be in use.

For a feature you want to use tomorrow, ask: would I know this value at prediction time?

05

In code

Read
Python
import pandas as pd

df = pd.DataFrame({"customer": ["a", "a", "a", "b"], "total": [1, 2, 3, 10]})
df["customer_avg"] = df.groupby("customer")["total"].transform("mean")
# The rolling mean of earlier rows only: shift first.
df["past_mean"] = df.groupby("customer")["total"].transform(
    lambda s: s.shift(1).rolling(2, min_periods=1).mean()
)
R
library(dplyr)
library(slider)

df <- tibble(customer = c("a", "a", "a", "b"), total = c(1, 2, 3, 10))
df <- df |>
  group_by(customer) |>
  mutate(
    customer_avg = mean(total),
    # The rolling mean of earlier rows only.
    past_mean = slide_dbl(total, mean, .before = 2, .after = -1)
  ) |>
  ungroup()
06

Check your understanding

Checkpoint

Check yourself

You want to flag orders much bigger than that customer's usual order. Which step fits?

Show the answer

Answer: b

You need the order and the customer's average on one row. Group statistic keeps every row and adds the average.

Check yourself

Group A has 3 orders averaging 10, and group B has 1 order averaging 50. What is the mean across all 4 orders?

Show the answer

Answer: 20

(3 × 10 + 1 × 50) / 4. Weight each mean by its count.

Check yourself

You build a churn model with the feature "average spend over the seven days centered on the prediction date". What's the problem?

Show the answer

Answer: b

A centered window looks forward. Use a window that ends before the prediction date.

07

Recap

Recap
  • Summarizing changes the unit; a group statistic keeps every row.
  • Keep counts, or the mean of means will mislead you.
  • A window that can see the future will flatter any model that uses it.

Concepts in this lesson