Sub topic 12
Rolling window expressions
This chapter covers fixed-size and time-based moving statistics in Polars. It assumes you can write group_by and agg expressions and that you know over from the previous chapters. You should also be comfortable reading a DataFrame printout and know what a null is.
What a rolling window is
A rolling window slides along an ordered column. For each row, Polars looks at a small group of nearby rows, applies a statistic such as a mean or sum, and writes one result for that row. The output has the same length as the input, like over, but the group is defined by position or time distance instead of by a key.
Typical uses are moving averages, trailing totals, and rolling volatility.
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")
)
print(out) # avg_3: null, null, 20.0, 30.0, 40.0The window for row 3 holds rows 1 to 3, so the mean is (10 + 20 + 30) / 3 = 20.0. Rows 1 and 2 do not yet have three values, so they are null.
The rolling expression family
Polars provides a rolling version of the common statistics. Each one is an expression method, so it works inside select, with_columns, and agg.
| Expression | Result for each row |
|---|---|
| `rolling_sum` | Sum of the values in the window |
| `rolling_mean` | Mean of the values in the window |
| `rolling_min`, `rolling_max` | Smallest or largest value in the window |
| `rolling_median` | Median of the window |
| `rolling_std`, `rolling_var` | Sample standard deviation or variance |
All of them take window_size, the number of rows in the window. They count rows, not time, so they assume consecutive rows are evenly spaced. If your data has gaps, use the time-based versions described later.
Window edges: min_samples and center
By default a result is produced only when the window is full. Two parameters change that.
min_samplesis the least number of non-null values a window needs to produce a result. It defaults towindow_size.center=Trueplaces the window around the current row instead of ending at it.
import polars as pl
daily = pl.DataFrame({"sales": [10, 20, 30, 40, 50]})
out = daily.with_columns(
pl.col("sales").rolling_mean(window_size=3, min_samples=1).alias("partial"),
pl.col("sales").rolling_mean(window_size=3, center=True).alias("centered"),
)
print(out)
# partial: 10.0, 15.0, 20.0, 30.0, 40.0
# centered: null, 20.0, 30.0, 40.0, nullWith min_samples=1, the first row averages only itself and the second averages two values, so no nulls appear at the start. With center=True, row 3 uses rows 2 to 4, and the first and last rows lack a full window.
Nulls inside a window
A null in the data counts against min_samples. With the default min_samples=window_size, any null in a window makes that window's result null.
import polars as pl
df = pl.DataFrame({"x": [1, None, 3, 4]})
out = df.with_columns(
pl.col("x").rolling_sum(window_size=2).alias("strict"),
pl.col("x").rolling_sum(window_size=2, min_samples=1).alias("lenient"),
)
print(out)
# strict: null, null, null, 7
# lenient: 1, 1, 3, 7The lenient version sums whatever non-null values exist in each window. Choose deliberately: lenient windows hide missing data, and strict windows spread one null across window_size output rows.
Rolling within groups
A rolling expression looks at neighbouring rows regardless of which group they belong to. If your table holds several regions stacked together, the window at the start of the second region would reach into the end of the first. Add over to restart the window in each group.
import polars as pl
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.0Without .over("region"), the third row would average 20 and 5, which mixes two regions. With it, each region starts fresh and gets its own leading null.
Time-based windows
A window measured in rows is wrong when observations are unevenly spaced. The _by variants, such as rolling_mean_by, define the window by a time distance on a date or datetime column. The same family exists for sum, min, max, median, std, and var.
import polars as pl
from datetime import datetime
df = pl.DataFrame({
"ts": [
datetime(2026, 1, 1),
datetime(2026, 1, 2),
datetime(2026, 1, 3),
datetime(2026, 1, 6),
],
"value": [10, 20, 30, 40],
}).sort("ts")
out = df.with_columns(
pl.col("value").rolling_mean_by("ts", window_size="2d").alias("avg_2d")
)
print(out) # avg_2d: 10.0, 15.0, 25.0, 40.0The window size is a duration string such as "2d", "1h", or "1w". For the row on January 6, no earlier row falls within two days, so the mean is just 40. A row-count window of size 2 would have averaged 30 and 40, which hides the gap.
The closed parameter controls whether each end of the window is included. Its default is "right": the window covers the interval after time - 2d up to and including time. For daily data that means the current day and the previous day. The time column must be sorted. For these _by methods, min_samples defaults to 1, so partial windows still produce a value.
The rolling context
DataFrame.rolling is the context version. It takes an index column and a period, and you write the statistics inside agg. Use it when you want several rolling statistics in one call.
import polars as pl
from datetime import datetime
df = pl.DataFrame({
"ts": [
datetime(2026, 1, 1),
datetime(2026, 1, 2),
datetime(2026, 1, 3),
datetime(2026, 1, 6),
],
"value": [10, 20, 30, 40],
}).sort("ts")
out = df.rolling(index_column="ts", period="2d").agg(
pl.col("value").mean().alias("mean_2d"),
pl.col("value").max().alias("max_2d"),
pl.len().alias("n"),
)
print(out)
# mean_2d: 10.0, 15.0, 25.0, 40.0
# max_2d: 10, 20, 30, 40
# n: 1, 2, 2, 1Because it is a context, any aggregation expression works inside agg, including ones that have no rolling_* method, such as a filtered count. The result has one row per input row, with the index column first. To roll per group, pass group_by="region" to rolling.
Rolling windows compared with nearby tools
| Tool | Rows in the result | Window defined by |
|---|---|---|
| `group_by(...).agg` | One per group | Key value |
| `expr.over(...)` | Same as input | Key value, whole group |
| `rolling_*` expression | Same as input | Neighbouring rows |
| `rolling_*_by` / `rolling` | Same as input | Time distance |
| `group_by_dynamic` | One per time bucket | Fixed, non-overlapping buckets |
The main difference from group_by_dynamic, covered in the next chapter, is overlap. A rolling window produces one overlapping window per row. A dynamic group produces one result per bucket, and buckets do not overlap by default.
Common errors
- Unsorted data. Results look plausible but are meaningless. Sort by the time column first. The
_bymethods androllingexpect a sorted column. - Leading nulls mistaken for bugs. The first
window_size - 1rows are null by design. Lowermin_samplesif you want values there. - Windows crossing groups. Forgetting
.over(...)orgroup_by=lets one group's rows leak into another. - Row windows on irregular data. If timestamps have gaps,
window_size=3means three observations, not three days. Userolling_mean_byinstead. - Integer window sizes with
_by. The_bymethods need a duration string such as"3d", not an integer, when the column is a date or datetime.
Exercise
A DataFrame df has columns store, day (an integer from 1 upward), and revenue. Write an expression that adds a column trailing_3 holding the mean revenue of the current day and the two previous days for each store. The first two days of each store should still get a value, based on the days available. State what must be done to the DataFrame before the expression runs.
Show answer
First sort the DataFrame so each store's rows are in day order: df = df.sort("store", "day"). Then use df.with_columns(pl.col("revenue").rolling_mean(window_size=3, min_samples=1).over("store").alias("trailing_3")). The .over("store") restarts the window for each store, and min_samples=1 lets the first two days average the rows that exist.
Exercise
A table of sensor readings has a sorted datetime column ts and a numeric column temp, with irregular gaps between readings. Why is rolling_mean(window_size=3) a poor choice for a "last 3 hours" average, and what should you use instead?
Show answer
rolling_mean(window_size=3) averages the last three rows, whatever their timestamps, so with gaps the rows may span many hours. Use pl.col("temp").rolling_mean_by("ts", window_size="3h"), which defines the window by elapsed time. With the default closed="right", the window covers the interval after ts - 3h up to and including ts.