polars.Expr.rolling_apply#

Expr.rolling_apply(
function: Callable[[Series], Any],
window_size: int,
weights: list[float] | None = None,
min_periods: int | None = None,
*,
center: bool = False,
) Self[source]#

Apply a custom rolling window function.

Prefer the specific rolling window functions over this one, as they are faster.

Prefer:

  • rolling_min

  • rolling_max

  • rolling_mean

  • rolling_sum

The window at a given row will include the row itself and the window_size - 1 elements before it.

Parameters:
function

Aggregation function

window_size

The length of the window.

weights

An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

min_periods

The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

center

Set the labels at the center of the window

Examples

>>> df = pl.DataFrame(
...     {
...         "A": [1.0, 2.0, 9.0, 2.0, 13.0],
...     }
... )
>>> df.select(
...     [
...         pl.col("A").rolling_apply(lambda s: s.std(), window_size=3),
...     ]
... )
 shape: (5, 1)
┌──────────┐
│ A        │
│ ---      │
│ f64      │
╞══════════╡
│ null     │
│ null     │
│ 4.358899 │
│ 4.041452 │
│ 5.567764 │
└──────────┘