polars.reduce#
- polars.reduce(
- function: Callable[[Series, Series], Series],
- exprs: Sequence[Expr | str] | Expr,
- *,
- returns_scalar: bool = False,
- return_dtype: DataTypeExpr | PolarsDataType | None = None,
Accumulate over multiple columns horizontally/ row wise with a left fold.
- 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.
- returns_scalar
Whether or not
function
applied returns a scalar. This must be set correctly by the user.- return_dtype
Output datatype. If not set, the dtype will be inferred based on the dtype of the input expressions.
Notes
See
fold
for the version with an explicit accumulator.Examples
>>> df = pl.DataFrame( ... { ... "a": [1, 2, 3], ... "b": [0, 1, 2], ... } ... ) >>> df shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 0 │ │ 2 ┆ 1 │ │ 3 ┆ 2 │ └─────┴─────┘
Horizontally sum over all columns.
>>> df.select( ... pl.reduce(function=lambda acc, x: acc + x, exprs=pl.col("*")).alias("sum") ... ) shape: (3, 1) ┌─────┐ │ sum │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 3 │ │ 5 │ └─────┘