Sub topic 13
Time-bucketed aggregation with group_by_dynamic
This chapter assumes you know group_by with agg, can build a Polars DataFrame, and understand rolling expressions from the previous chapter. Here you will aggregate rows into fixed time intervals with group_by_dynamic.
Why a separate method
A normal group_by groups by exact values. Timestamps are rarely equal, so grouping on them gives one group per row. To get "total per day" or "average per hour", you need to bucket the timestamps first. group_by_dynamic does the bucketing and the aggregation in one step.
Each bucket is a window that starts at a boundary and spans a fixed length. The every argument sets how often a new window starts. The output has one row per window, labeled by the window start.
A first example
import polars as pl
from datetime import datetime
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 two events fall on January 1, so their values sum to 3. The third event falls on January 2 and forms its own bucket.
The sorted-key requirement
The time column must be sorted in ascending order. Polars does not sort it for you. If the data is unsorted, the result can be wrong, and Polars may raise an error or warn that the column is not sorted. Sort first:
events = events.sort("ts")Interval strings
The every argument takes a duration string made of a number and a unit.
| Unit | Meaning |
|---|---|
| `s` | second |
| `m` | minute |
| `h` | hour |
| `d` | day |
| `w` | week |
| `mo` | month |
| `y` | year |
You can combine units, such as "1h30m". Calendar units like mo follow the calendar, so buckets can differ in real length.
Window length and overlap
By default, the window length equals every, so windows tile the timeline without gaps or overlap. The period argument sets a different length. If period is longer than every, windows overlap and a row can appear in several of them. If it is shorter, some rows fall in no window.
out = events.group_by_dynamic("ts", every="1d", period="2d").agg(
pl.col("value").sum().alias("two_day_total")
)
print(out)Here the January 1 window covers both days and sums to 6. The January 2 window covers only the third event and sums to 3.
Grouping by another column too
Pass group_by to compute buckets separately within each group, for example per sensor:
readings = pl.DataFrame({
"ts": [datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 10), datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 11)],
"sensor": ["a", "a", "b", "b"],
"temp": [20.0, 22.0, 18.0, 19.0],
}).sort("sensor", "ts")
out = readings.group_by_dynamic("ts", every="1h", group_by="sensor").agg(
pl.col("temp").mean().alias("avg_temp")
)
print(out)The time column must be sorted within each group.
Comparison with rolling
A rolling expression keeps one output row per input row. group_by_dynamic returns one row per bucket, so the height changes. Use rolling for a moving statistic on every row. Use group_by_dynamic for a report per time interval.
Exercise
You have a sorted DataFrame with a datetime column ts and a numeric column amount. Write the call that returns the total amount for each hour. Then say what happens to an hour that has no rows.
Show answer
Use df.group_by_dynamic("ts", every="1h").agg(pl.col("amount").sum().alias("hourly_total")). An hour with no rows does not appear in the output, so there is no row with a zero. To include it, build a range with pl.datetime_range, join the result onto it, and fill the nulls.