Skip to content

Clip elements

Source code

Description

Set values outside the given boundaries to the boundary value. This only works for numeric and temporal values.

Usage

<Expr>$clip(lower_bound = NULL, upper_bound = NULL)

Arguments

lower_bound Lower bound. Accepts expression input. Strings are parsed as column names and other non-expression inputs are parsed as literals.
upper_bound Upper bound. Accepts expression input. Strings are parsed as column names and other non-expression inputs are parsed as literals.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(foo = c(-50L, 5L, NA_integer_, 50L), bound = c(1, 10, 1, 1))

# With the two bounds
df$with_columns(clipped = pl$col("foo")$clip(1, 10))
#> shape: (4, 3)
#> ┌──────┬───────┬─────────┐
#> │ foo  ┆ bound ┆ clipped │
#> │ ---  ┆ ---   ┆ ---     │
#> │ i32  ┆ f64   ┆ i32     │
#> ╞══════╪═══════╪═════════╡
#> │ -50  ┆ 1.0   ┆ 1       │
#> │ 5    ┆ 10.0  ┆ 5       │
#> │ null ┆ 1.0   ┆ null    │
#> │ 50   ┆ 1.0   ┆ 10      │
#> └──────┴───────┴─────────┘
# Without lower bound
df$with_columns(clipped = pl$col("foo")$clip(upper_bound = 10))
#> shape: (4, 3)
#> ┌──────┬───────┬─────────┐
#> │ foo  ┆ bound ┆ clipped │
#> │ ---  ┆ ---   ┆ ---     │
#> │ i32  ┆ f64   ┆ i32     │
#> ╞══════╪═══════╪═════════╡
#> │ -50  ┆ 1.0   ┆ -50     │
#> │ 5    ┆ 10.0  ┆ 5       │
#> │ null ┆ 1.0   ┆ null    │
#> │ 50   ┆ 1.0   ┆ 10      │
#> └──────┴───────┴─────────┘
# Using another column as lower bound
df$with_columns(clipped = pl$col("foo")$clip(lower_bound = "bound"))
#> shape: (4, 3)
#> ┌──────┬───────┬─────────┐
#> │ foo  ┆ bound ┆ clipped │
#> │ ---  ┆ ---   ┆ ---     │
#> │ i32  ┆ f64   ┆ i32     │
#> ╞══════╪═══════╪═════════╡
#> │ -50  ┆ 1.0   ┆ 1       │
#> │ 5    ┆ 10.0  ┆ 10      │
#> │ null ┆ 1.0   ┆ null    │
#> │ 50   ┆ 1.0   ┆ 50      │
#> └──────┴───────┴─────────┘