Grouping over time in Python
group_by_dynamic buckets rows by a time window, like a resample.
import polars as pl
frame = pl.DataFrame({
"at": pl.datetime_range(
pl.datetime(2026, 7, 27), pl.datetime(2026, 8, 2),
interval="1d", eager=True),
"tpm": [88, 91, 97, 104, 99, 108, 102],
}).sort("at")
weekly = frame.group_by_dynamic("at", every="3d").agg(
pl.len().alias("runs"),
pl.col("tpm").mean().round(1).alias("mean_tpm"),
)
print(weekly)
rolling = frame.with_columns(
pl.col("tpm").rolling_mean(window_size=3).round(1).alias("rolling3"))
print(rolling.tail(3))
How it works
- The frame must be sorted on the time column.
everyis the bucket size;periodcan overlap them.- Empty windows appear or not depending on the arguments.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 18
- Characters to type
- 470
- Tokens
- 186
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 101 seconds.
Step 2 of 2 in Time series, step 24 of 32 in Polars.