polars.Expr.pipe_with_dtype#
- Expr.pipe_with_dtype(function: Callable[[Expr, DataType], IntoExpr]) Expr[source]#
Converts to another expression by calling
function.Runs during the plan stage (unlike
pipe_with_schema), which means that the dytype of this expression is known. This allows choosing a different expression depending on the dtype of the input, including the metadata of extension types. This also means that any exceptions raised byfunctionwill only be emitted during the plan stage.Warning
This functionality is considered unstable. It may be changed at any point without it being considered a breaking change.
- Parameters:
- function
Callable; will receive the expression as the first parameter and its resolved dtype as the second parameter. The returned expression takes the place of this expression, including its output name.
See also
pipepolars.pipe_with_dtypePass multiple expressions to a single function.
LazyFrame.pipe_with_schema
Examples
Cast integer and string columns to float, but leave the other columns as-is.
>>> def to_float_if_possible(expr: pl.Expr, dtype: pl.DataType) -> pl.Expr: ... if dtype.is_integer() or dtype == pl.String: ... return expr.cast(pl.Float64) ... return expr >>> df = pl.DataFrame( ... {"a": [1, 2], "b": ["1.0", "2.5"], "c": [2.0, 3.0], "d": [[1], [2, 3]]}, ... schema={ ... "a": pl.Int64, ... "b": pl.String, ... "c": pl.Float32, ... "d": pl.List(pl.Int64), ... }, ... ) >>> df.select(pl.all().pipe_with_dtype(to_float_if_possible)) shape: (2, 4) ┌─────┬─────┬─────┬───────────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ f32 ┆ list[i64] │ ╞═════╪═════╪═════╪═══════════╡ │ 1.0 ┆ 1.0 ┆ 2.0 ┆ [1] │ │ 2.0 ┆ 2.5 ┆ 3.0 ┆ [2, 3] │ └─────┴─────┴─────┴───────────┘