Sub topic 13
Time-bucketed aggregation with group_by_dynamic
This chapter assumes you already know group_by with agg, expressions such as pl.col("x").sum(), and how to build a DataFrame with a datetime column. It builds on the earlier chapter on rolling window expressions and shows how to bucket ordered data by time.
Why a regular group_by is not enough
A plain group_by("region") groups rows that share an exact key value. Timestamps rarely repeat exactly, so grouping on a raw timestamp gives one group per row. What you usually want is one group per day, hour, or month. group_by_dynamic creates those time windows for you and aggregates each one.
It differs from group_by in three ways:
- It takes an index column, which must be sorted, and cuts it into windows.
- The windows are generated from the
every,period, andoffsetsettings. They are not read from the data. - Each output row is labeled with the window start, not with a key found in the data.
The basic call
from datetime import datetime
import polars as pl
events = pl.DataFrame({
"ts": [datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 15), datetime(2026, 1, 2, 10)],
"value": [1, 2, 3],
})
out = events.group_by_dynamic("ts", every="1d").agg(
pl.col("value").sum().alias("daily_total")
)
print(out) # 2026-01-01: 3; 2026-01-02: 3The first argument is the index column. every="1d" sets the spacing between window starts. The two events on January 1 land in the bucket labeled 2026-01-01 00:00:00. The agg step works as it does in group_by, so you can pass several expressions.
The interval strings use a compact syntax. The units are ns, us, ms, s, m, h, d, w, mo, q, and y. You can combine them, as in "1h30m". Calendar units such as "1mo" follow real month lengths. An integer index column uses an i suffix, such as "2i".
Window parameters
| Parameter | Default | Effect |
|---|---|---|
| `every` | required | Spacing between window starts. |
| `period` | same as `every` | Length of each window. A longer period gives overlapping windows. |
| `offset` | none | Shifts every window start by a fixed amount. |
| `closed` | `"left"` | Which window edges include a row: `"left"`, `"right"`, `"both"`, or `"none"`. |
| `label` | `"left"` | Which boundary labels the row: `"left"`, `"right"`, or `"datapoint"`. |
| `include_boundaries` | `False` | Adds `_lower_boundary` and `_upper_boundary` columns. |
| `group_by` | none | Column or columns to group by before bucketing. |
| `start_by` | `"window"` | How the first window start is chosen. |
The defaults give half-open windows [start, start + every). A row exactly on a boundary belongs to the window that starts there.
Shifting windows with offset
With offset, you can make a "business day" start at 06:00 instead of midnight.
shifted = events.group_by_dynamic("ts", every="1d", offset="6h").agg(
pl.col("value").sum().alias("total")
)
print(shifted) # 2026-01-01 06:00: 3; 2026-01-02 06:00: 3Both January 1 events fall after 06:00, so they stay together. An event at 03:00 would belong to the previous day's window.
Grouping by another column too
Pass group_by to bucket within each key. This is the usual shape for per-sensor or per-customer metrics.
readings = pl.DataFrame({
"ts": [
datetime(2026, 1, 1, 0, 10),
datetime(2026, 1, 1, 0, 40),
datetime(2026, 1, 1, 1, 5),
datetime(2026, 1, 1, 0, 20),
datetime(2026, 1, 1, 1, 50),
],
"sensor": ["a", "a", "a", "b", "b"],
"temp": [20.0, 22.0, 24.0, 30.0, 34.0],
})
hourly = (
readings.sort("ts")
.group_by_dynamic("ts", every="1h", group_by="sensor")
.agg(
pl.col("temp").mean().alias("avg_temp"),
pl.len().alias("n"),
)
.sort("sensor", "ts")
)
print(hourly)
# a, 00:00 -> avg 21.0, n 2
# a, 01:00 -> avg 24.0, n 1
# b, 00:00 -> avg 30.0, n 1
# b, 01:00 -> avg 34.0, n 1The final sort matters. As with group_by, the order of the output groups is not guaranteed.
Sorting is required
The index column must be sorted in ascending order. When you use group_by=, it must be sorted within each group. Sorting the whole frame by the index column satisfies both conditions.
Empty windows are not produced
group_by_dynamic only emits windows that contain at least one row. If no events happened on January 2, that day is missing from the output, not shown as zero. Charts and downstream joins often need the gap filled. Use upsample on the result, then fill the nulls.
sparse = pl.DataFrame({
"ts": [datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 15), datetime(2026, 1, 3, 10)],
"value": [1, 2, 3],
})
daily = sparse.group_by_dynamic("ts", every="1d").agg(
pl.col("value").sum().alias("daily_total")
)
print(daily) # only Jan 1 (3) and Jan 3 (3)
filled = daily.upsample(time_column="ts", every="1d").fill_null(0)
print(filled) # Jan 1: 3, Jan 2: 0, Jan 3: 3upsample inserts the missing rows and leaves their other columns null. Choose the fill value deliberately. Zero suits counts and sums. It is wrong for averages, where null often means "no data".
Integer index columns
The index column does not have to be a date. An integer column of type Int32 or Int64 works with an i suffix.
ticks = pl.DataFrame({"t": [0, 1, 2, 3, 4, 5], "v": [1, 1, 1, 1, 1, 1]})
print(ticks.group_by_dynamic("t", every="2i").agg(pl.col("v").sum()))
# windows start at 0, 2, 4; each total is 2group_by_dynamic or truncate plus group_by
For simple, non-overlapping buckets you can get the same result by truncating the timestamp and using a normal group_by.
alt = (
events.group_by(pl.col("ts").dt.truncate("1d"))
.agg(pl.col("value").sum().alias("daily_total"))
.sort("ts")
)
print(alt) # same two rows as the first example| Need | Better choice |
|---|---|
| Unsorted data, simple fixed buckets | `dt.truncate` with `group_by` |
| Overlapping windows (`period` longer than `every`) | `group_by_dynamic` |
| Calendar-aware windows, custom `offset`, `closed`, or `label` | `group_by_dynamic` |
| A value on every row, not one row per bucket | `rolling` or `over` |
| Several keys bucketed together | Either; `group_by_dynamic` with `group_by=` is the clearer form |
Common errors
- Forgetting to sort. This causes an error or, in older versions, wrong output. Sort by the index column first.
- Expecting zero rows for empty buckets. Add
upsampleor join against a generated date range. - Misreading labels. The default label is the window start. A bucket labeled
01-01covers01-01up to but not including01-02. - Using
everyandperiodinterchangeably. Ifperiodis longer thanevery, one row can fall into several windows, so totals across windows add up to more than the column total. - Mixing time zones. Truncation of calendar units uses the column's time zone, so a daily bucket for a zoned column starts at local midnight.
Lazy use
LazyFrame has the same group_by_dynamic method with the same arguments. Build the query with .lazy() and call .collect() at the end. The sort requirement still applies, so include .sort("ts") in the lazy chain when the source order is not guaranteed.
Exercise
A sensor frame has columns ts (datetime), sensor (string), and temp (float). You call readings.groupbydynamic("ts", every="1h", group_by="sensor").agg(pl.col("temp").max()) and sensor "b" had no readings between 02:00 and 03:00. What does the output contain for sensor "b" in that hour, and how would you add it?
Show answer
The output has no row for sensor "b" in the 02:00 window, because groupbydynamic only emits windows that contain data. To add the row, call upsample on the result with timecolumn="ts", every="1h", and groupby="sensor", then fill the null max with a suitable value or leave it null. The frame must be sorted by ts first.
Exercise
Which setting changes a daily bucket so it starts at 06:00 instead of midnight, and what label does the bucket containing a 09:00 event on January 1 receive by default?
Show answer
Set offset="6h" in groupbydynamic. The bucket gets the label 2026-01-01 06:00:00, because label defaults to "left", the window start.