Time-Series in Polars: group_by_rolling for Window Analysis

3D visualization of parallel conveyor belts with sliding windows calculating data for different groups, representing Polars group_by_rolling.

We’ve covered two types of window functions in Polars. Now, we’ll look at how to use Polars group_by_rolling functionality.

  1. .rolling(): A centered window based on time (e.g., “3-day average”).
  2. .group_by_dynamic(): Groups by time bins (e.g., “all sales per month”).

group_by_rolling() is the third type. It’s an index-based rolling group. It creates a rolling window of a fixed number of rows.

The Syntax

group_by_rolling is used to define the groups, then you agg the results.

import polars as pl
df = pl.DataFrame({
    "value": [1, 2, 3, 4, 100, 101, 102]
})

# We want to create a 3-row rolling sum.
# The 'index_column' is just the row number.
# We create it using pl.int_range()
df_rolling = df.with_row_count(name="index").group_by_rolling(
    index_column="index", 
    period="3i"  # "3i" = 3 indexes (3 rows)
).agg(
    pl.col("value").sum().alias("sum_3_rows")
)

print(df_rolling)

Output:

shape: (7, 2)
┌───────┬────────────┐
│ index ┆ sum_3_rows │
│ ---   ┆ ---        │
│ u32   ┆ i64        │
╞═══════╪════════════╡
│ 0     ┆ 1          │
│ 1     ┆ 3          │
│ 2     ┆ 6          │
│ 3     ┆ 9          │
│ 4     ┆ 107        │
│ 5     ┆ 205        │
│ 6     ┆ 303        │
└───────┴────────────┘

How to read this:

  • Row 2 (index 2): Sum of rows [0, 1, 2] -> 1 + 2 + 3 = 6
  • Row 3 (index 3): Sum of rows [1, 2, 3] -> 2 + 3 + 4 = 9
  • Row 4 (index 4): Sum of rows [2, 3, 4] -> 3 + 4 + 100 = 107

This is extremely fast and useful for signal processing or financial data where you need a fixed-size (not time-based) window.


Key Takeaways

  • This article discusses three types of window functions in Polars: .rolling(), .group_by_dynamic(), and group_by_rolling.
  • group_by_rolling is an index-based rolling group, creating a fixed window of rows for aggregation.
  • You define groups with group_by_rolling, then use agg to summarise the results efficiently.
  • The example shows how to calculate rolling sums, which are beneficial for signal processing and financial data.

Similar Posts

Leave a Reply