Skip to content

Replace the given values by different values of the same data type.

Source code

Description

This allows one to recode values in a column, leaving all other values unchanged. See $replace_strict() to give a default value to all other values and to specify the output datatype.

Usage

<Expr>$replace(old, new)

Arguments

old Can be several things:
  • a vector indicating the values to recode;
  • if new is missing, this can be a named list e.g list(old = “new”) where the names are the old values and the values are the replacements. Note that if old values are numeric, the names must be wrapped in backticks;
  • an Expr
new Either a vector of length 1, a vector of same length as old or an Expr. If missing, old must be a named list.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(a = c(1, 2, 2, 3))

# "old" and "new" can take vectors of length 1 or of same length
df$with_columns(replaced = pl$col("a")$replace(2, 100))
#> shape: (4, 2)
#> ┌─────┬──────────┐
#> │ a   ┆ replaced │
#> │ --- ┆ ---      │
#> │ f64 ┆ f64      │
#> ╞═════╪══════════╡
#> │ 1.0 ┆ 1.0      │
#> │ 2.0 ┆ 100.0    │
#> │ 2.0 ┆ 100.0    │
#> │ 3.0 ┆ 3.0      │
#> └─────┴──────────┘
df$with_columns(replaced = pl$col("a")$replace(c(2, 3), c(100, 200)))
#> shape: (4, 2)
#> ┌─────┬──────────┐
#> │ a   ┆ replaced │
#> │ --- ┆ ---      │
#> │ f64 ┆ f64      │
#> ╞═════╪══════════╡
#> │ 1.0 ┆ 1.0      │
#> │ 2.0 ┆ 100.0    │
#> │ 2.0 ┆ 100.0    │
#> │ 3.0 ┆ 200.0    │
#> └─────┴──────────┘
# "old" can be a named list where names are values to replace, and values are
# the replacements
mapping = list(`2` = 100, `3` = 200)
df$with_columns(replaced = pl$col("a")$replace(mapping))
#> shape: (4, 2)
#> ┌─────┬──────────┐
#> │ a   ┆ replaced │
#> │ --- ┆ ---      │
#> │ f64 ┆ f64      │
#> ╞═════╪══════════╡
#> │ 1.0 ┆ 1.0      │
#> │ 2.0 ┆ 100.0    │
#> │ 2.0 ┆ 100.0    │
#> │ 3.0 ┆ 200.0    │
#> └─────┴──────────┘
df = pl$DataFrame(a = c("x", "y", "z"))
mapping = list(x = 1, y = 2, z = 3)
df$with_columns(replaced = pl$col("a")$replace(mapping))
#> shape: (3, 2)
#> ┌─────┬──────────┐
#> │ a   ┆ replaced │
#> │ --- ┆ ---      │
#> │ str ┆ str      │
#> ╞═════╪══════════╡
#> │ x   ┆ 1.0      │
#> │ y   ┆ 2.0      │
#> │ z   ┆ 3.0      │
#> └─────┴──────────┘
# "old" and "new" can take Expr
df = pl$DataFrame(a = c(1, 2, 2, 3), b = c(1.5, 2.5, 5, 1))
df$with_columns(
  replaced = pl$col("a")$replace(
    old = pl$col("a")$max(),
    new = pl$col("b")$sum()
  )
)
#> shape: (4, 3)
#> ┌─────┬─────┬──────────┐
#> │ a   ┆ b   ┆ replaced │
#> │ --- ┆ --- ┆ ---      │
#> │ f64 ┆ f64 ┆ f64      │
#> ╞═════╪═════╪══════════╡
#> │ 1.0 ┆ 1.5 ┆ 1.0      │
#> │ 2.0 ┆ 2.5 ┆ 2.0      │
#> │ 2.0 ┆ 5.0 ┆ 2.0      │
#> │ 3.0 ┆ 1.0 ┆ 10.0     │
#> └─────┴─────┴──────────┘