Cumulative metrics
Select a running total from a DataFrame or LazyFrame query.
Polars · Module
Returns an expression that computes a running sum for the named column values. It is shorthand for applying Expr.cum_sum to a column expression.
pl.cum_sum selects a column and returns an expression whose value at each row is the running total through that row. It is shorthand for selecting the column expression and calling its cum_sum method; use cum_sum_horizontal for row-wise accumulation across columns.
polars.cum_sum(names: str) -> Expr| Name | Type | Description |
|---|---|---|
names | str | Name(s) of the columns to use in the aggregation. |
Expr
import polars as pl
df = pl.DataFrame({"a": [1, 2, 3]})
result = df.select(pl.cum_sum("a"))
print(result)Creates a cumulative total for column a, producing 1, 3, and 6.
Select a running total from a DataFrame or LazyFrame query.
Build expression pipelines without manually constructing pl.col(name).cum_sum().
Choose between vertical and row-wise cumulative aggregation.
It returns an expression containing the cumulative sum of the named column. The function is syntactic sugar for col(names).cum_sum().
Follow-up: How would you calculate cumulative totals across several columns in each row? Use cum_sum_horizontal rather than this vertical column operation.
The names parameter identifies the column or columns used in the aggregation. The returned expression can be passed to DataFrame.select or another expression context.
Follow-up: What happens when the expression is used in a lazy query? It remains part of the query plan until collection, allowing Polars to optimize the surrounding computation.
For a column containing 1, 2, and 3, selecting pl.cum_sum("a") yields 1, 3, and 6. Each output row includes the current value plus all preceding values.
Follow-up: Which related function should be chosen for horizontal accumulation? Choose cum_sum_horizontal when values from multiple columns must be accumulated across each row.
polars.Expr.cum_sumpolars.cum_sum_horizontalpolars.col