Sub topic 12
Rolling window expressions
This chapter assumes you can write with_columns and group_by expressions and know what over does. Here you will compute moving statistics, such as a three-day average, without reducing the number of rows.
What a rolling window does
A rolling expression looks at a fixed-size window of neighboring rows and computes one value for each row. The window slides down the column one row at a time. Unlike group_by, the output has the same height as the input. Unlike a plain over, the window is defined by position, not by a group key.
import polars as pl
daily = pl.DataFrame({
"day": [1, 2, 3, 4, 5],
"sales": [10, 20, 30, 40, 50],
})
out = daily.with_columns(
pl.col("sales").rolling_mean(window_size=3).alias("avg_3"),
pl.col("sales").rolling_sum(window_size=3).alias("sum_3"),
)
print(out) # avg_3: null, null, 20.0, 30.0, 40.0; sum_3: null, null, 60, 90, 120Each window covers the current row and the two rows before it. The first two rows have no full window, so the result is null.
Common rolling expressions
Polars provides rolling_mean, rolling_sum, rolling_min, rolling_max, rolling_std, rolling_var, and rolling_median. They all take the same main parameters.
| Parameter | Meaning |
|---|---|
| `window_size` | Number of rows in the window, including the current row |
| `min_samples` | Minimum non-null values needed to produce a result. It defaults to `window_size`. |
| `center` | If `True`, the window is centered on the current row instead of ending at it |
Older Polars versions call min_samples by the name min_periods. Check which one your installed version accepts.
Filling the leading nulls
Set min_samples lower to get a value from a partial window.
out = daily.with_columns(
pl.col("sales").rolling_mean(window_size=3, min_samples=1).alias("avg_3")
)
print(out) # avg_3: 10.0, 15.0, 20.0, 30.0, 40.0The first value is the mean of one row, the second is the mean of two rows, and so on. This is useful, but the early values are based on less data. Don't compare them to full-window values without noting that.
Rolling within groups
A rolling expression ignores group boundaries. If a table holds several regions, the window will mix rows from neighboring regions. Add over so the window restarts in each group.
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
})
out = df.with_columns(
pl.col("sales").rolling_mean(window_size=2).over("region").alias("avg_2")
)
print(out) # avg_2: null, 15.0, null, 10.0, 20.0The first west row is null even though a row sits before it. That row belongs to east, so it is not in the window.
Common errors
- Unsorted data. Rolling windows follow row order. Sort first, for example with
df.sort("day"), or the average will cover arbitrary neighbors. - Forgetting
over. Without it, windows span group boundaries and produce plausible but wrong numbers. - Expecting a smaller table. Rolling keeps every row. To get one row per time bucket, use
group_by_dynamic, covered in the next chapter. - Row counts versus time spans.
window_size=3means three rows, not three days. If days are missing, the window covers a longer span. For time-based windows, use therolling_*_byvariants, such asrolling_mean_by("ts", window_size="3d"). They take a sorted datetime column and a duration string.
Exercise
A table has columns store and sales, already sorted by date within each store. Write the expression that adds a column avg_2 holding the mean of the current and previous row's sales, computed separately for each store, with no nulls in the first row of each store.
Show answer
df.withcolumns(pl.col("sales").rollingmean(windowsize=2, minsamples=1).over("store").alias("avg2")). The over("store") restarts the window at each store, and `minsamples=1` lets the first row use a partial window.