polars.Expr.clip#
- Expr.clip(
- lower_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
- upper_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
Set values outside the given boundaries to the boundary value.
- Parameters:
- lower_bound
Lower bound. Accepts expression input. Non-expression inputs are parsed as literals. Strings are parsed as column names.
- upper_bound
Upper bound. Accepts expression input. Non-expression inputs are parsed as literals. Strings are parsed as column names.
See also
Notes
This method only works for numeric and temporal columns. To clip other data types, consider writing a
when-then-otherwise
expression. Seewhen()
.Examples
Specifying both a lower and upper bound:
>>> df = pl.DataFrame({"a": [-50, 5, 50, None]}) >>> df.with_columns(clip=pl.col("a").clip(1, 10)) shape: (4, 2) ┌──────┬──────┐ │ a ┆ clip │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ -50 ┆ 1 │ │ 5 ┆ 5 │ │ 50 ┆ 10 │ │ null ┆ null │ └──────┴──────┘
Specifying only a single bound:
>>> df.with_columns(clip=pl.col("a").clip(upper_bound=10)) shape: (4, 2) ┌──────┬──────┐ │ a ┆ clip │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ -50 ┆ -50 │ │ 5 ┆ 5 │ │ 50 ┆ 10 │ │ null ┆ null │ └──────┴──────┘
Using columns as bounds:
>>> df = pl.DataFrame( ... {"a": [-50, 5, 50, None], "low": [10, 1, 0, 0], "up": [20, 4, 3, 2]} ... ) >>> df.with_columns(clip=pl.col("a").clip("low", "up")) shape: (4, 4) ┌──────┬─────┬─────┬──────┐ │ a ┆ low ┆ up ┆ clip │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞══════╪═════╪═════╪══════╡ │ -50 ┆ 10 ┆ 20 ┆ 10 │ │ 5 ┆ 1 ┆ 4 ┆ 4 │ │ 50 ┆ 0 ┆ 3 ┆ 3 │ │ null ┆ 0 ┆ 2 ┆ null │ └──────┴─────┴─────┴──────┘