polars.coalesce — Polars documentation (original) (raw)

polars.coalesce(

exprs: IntoExpr | Iterable[IntoExpr],

*more_exprs: IntoExpr,

eager: bool = False,

) → Expr | Series[source]#

Folds the columns from left to right, keeping the first non-null value.

Parameters:

exprs

Columns to coalesce. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals.

*more_exprs

Additional columns to coalesce, specified as positional arguments.

eager

Evaluate immediately and return a Series; this requires that at least one of the given arguments is a Series. If set to False (default), return an expression instead.

Examples

df = pl.DataFrame( ... { ... "a": [1, None, None, None], ... "b": [1, 2, None, None], ... "c": [5, None, 3, None], ... } ... )

df.with_columns(pl.coalesce("a", "b", "c", 10).alias("d")) shape: (4, 4) ┌──────┬──────┬──────┬─────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞══════╪══════╪══════╪═════╡ │ 1 ┆ 1 ┆ 5 ┆ 1 │ │ null ┆ 2 ┆ null ┆ 2 │ │ null ┆ null ┆ 3 ┆ 3 │ │ null ┆ null ┆ null ┆ 10 │ └──────┴──────┴──────┴─────┘

df.with_columns(pl.coalesce(pl.col(["a", "b", "c"]), 10.0).alias("d")) shape: (4, 4) ┌──────┬──────┬──────┬──────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ f64 │ ╞══════╪══════╪══════╪══════╡ │ 1 ┆ 1 ┆ 5 ┆ 1.0 │ │ null ┆ 2 ┆ null ┆ 2.0 │ │ null ┆ null ┆ 3 ┆ 3.0 │ │ null ┆ null ┆ null ┆ 10.0 │ └──────┴──────┴──────┴──────┘

s1 = pl.Series("a", [None, 2, None]) s2 = pl.Series("b", [1, None, 3]) pl.coalesce(s1, s2, eager=True) shape: (3,) Series: 'a' [i64] [ 1 2 3 ]