polars.pipe_with_dtype#

polars.pipe_with_dtype(
exprs: Sequence[str | Expr],
function: Callable[[list[tuple[Expr, DataType]]], IntoExpr],
) → Expr[source]#

Replace exprs, at plan time, with the expression returned by function.

function is not executed immediately but only during the plan stage, once the dtypes of exprs are known. This allows choosing a different expression depending on the dtypes of the inputs, including the metadata of extension types. This also means that any exceptions raised by function will only be emitted during the plan stage.

If any of exprs expands to multiple columns (e.g. a selector), function is called once for every column, as with other functions taking multiple expressions. It may also be called more than once for the same inputs, for example when the schema is resolved separately. It should not have side effects.

Warning

This functionality is considered unstable. It may be changed at any point without it being considered a breaking change.

engine:In MemoryStreamingDistributed
Parameters:
exprs

Expression(s) whose dtypes are passed to function. Strings are parsed as column names.

function

Callable; will receive a list with an (expression, dtype) pair for every input, in the same order as exprs. The returned expression takes the place of the inputs, including its output name.

See also

Expr.pipe_with_dtype

Same functionality for a single expression.

LazyFrame.pipe_with_schema

Examples

Sum the inputs, unless one of them is a string, in which case they are concatenated instead.

>>> def sum_or_concat(inputs: list[tuple[pl.Expr, pl.DataType]]) -> pl.Expr:
...     exprs = [expr for expr, _ in inputs]
...     if any(dtype == pl.String for _, dtype in inputs):
...         return pl.concat_str(exprs)
...     return pl.sum_horizontal(exprs)
>>> df = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "y"]})
>>> df.select(
...     ab=pl.pipe_with_dtype(["a", "b"], sum_or_concat),
...     ac=pl.pipe_with_dtype(["a", "c"], sum_or_concat),
... )
shape: (2, 2)
┌─────┬─────┐
│ ab  ┆ ac  │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════╡
│ 4   ┆ 1x  │
│ 6   ┆ 2y  │
└─────┴─────┘