Skip to content

Coalesce

Source code

Description

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

Usage

pl$coalesce(...)

Arguments

is a: If one arg:
  • Series or Expr, same as column$sum()
  • string, same as pl$col(column)$sum()
  • numeric, same as pl$lit(column)$sum()
  • list of strings(column names) or expressions to add up as expr1 + expr2 + expr3 + …
If several args, then wrapped in a list and handled as above.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(
  a = NA_real_,
  b = c(1L, 4L, NA_real_, NA_real_),
  c = c(2:4, NA_real_)
)

# use coalesce to get first non Null value for each row, otherwise insert 99.9
df$with_columns(
  pl$coalesce("a", "b", "c", 99.9)$alias("d")
)
#> shape: (4, 4)
#> ┌──────┬──────┬──────┬──────┐
#> │ a    ┆ b    ┆ c    ┆ d    │
#> │ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞══════╪══════╪══════╪══════╡
#> │ null ┆ 1.0  ┆ 2.0  ┆ 1.0  │
#> │ null ┆ 4.0  ┆ 3.0  ┆ 4.0  │
#> │ null ┆ null ┆ 4.0  ┆ 4.0  │
#> │ null ┆ null ┆ null ┆ 99.9 │
#> └──────┴──────┴──────┴──────┘