polars.cum_reduce#

polars.cum_reduce(
function: Callable[[Series, Series], Series],
exprs: Sequence[Expr | str] | Expr,
) Expr[source]#

Cumulatively reduce horizontally across columns with a left fold.

Every cumulative result is added as a separate field in a Struct column.

Parameters:
function

Function to apply over the accumulator and the value. Fn(acc, value) -> new_value

exprs

Expressions to aggregate over. May also be a wildcard expression.

Examples

>>> df = pl.DataFrame(
...     {
...         "a": [1, 2, 3],
...         "b": [3, 4, 5],
...         "c": [5, 6, 7],
...     }
... )
>>> df.with_columns(pl.cum_reduce(function=lambda acc, x: acc + x, exprs=pl.all()))
shape: (3, 4)
┌─────┬─────┬─────┬────────────┐
│ a   ┆ b   ┆ c   ┆ cum_reduce │
│ --- ┆ --- ┆ --- ┆ ---        │
│ i64 ┆ i64 ┆ i64 ┆ struct[3]  │
╞═════╪═════╪═════╪════════════╡
│ 1   ┆ 3   ┆ 5   ┆ {1,4,9}    │
│ 2   ┆ 4   ┆ 6   ┆ {2,6,12}   │
│ 3   ┆ 5   ┆ 7   ┆ {3,8,15}   │
└─────┴─────┴─────┴────────────┘