polars.coalesce#

polars.coalesce(exprs: Sequence[polars.internals.expr.expr.Expr | str | datetime.date | datetime.datetime | datetime.timedelta | int | float | bool | polars.internals.series.series.Series]) Expr[source]#

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

Parameters:
exprs

Expressions to coalesce.

Examples

>>> df = pl.DataFrame(
...     data=[
...         (None, 1.0, 1.0),
...         (None, 2.0, 2.0),
...         (None, None, 3.0),
...         (None, None, None),
...     ],
...     columns=[("a", pl.Float64), ("b", pl.Float64), ("c", pl.Float64)],
... )
>>> df.with_column(pl.coalesce(["a", "b", "c", 99.9]).alias("d"))
shape: (4, 4)
┌──────┬──────┬──────┬──────┐
│ a    ┆ b    ┆ c    ┆ d    │
│ ---  ┆ ---  ┆ ---  ┆ ---  │
│ f64  ┆ f64  ┆ f64  ┆ f64  │
╞══════╪══════╪══════╪══════╡
│ null ┆ 1.0  ┆ 1.0  ┆ 1.0  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ null ┆ 2.0  ┆ 2.0  ┆ 2.0  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ null ┆ null ┆ 3.0  ┆ 3.0  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ null ┆ null ┆ null ┆ 99.9 │
└──────┴──────┴──────┴──────┘