Bound numeric values
Normalize measurements or scores to a permitted numeric range.
Polars · Module
Clips values outside optional lower and upper boundaries to those boundaries. It supports numeric and temporal expressions and can use literals or column-based bounds.
Use Expr.clip in a DataFrame expression to constrain numeric or temporal values. Each bound may be a literal or an expression; omitted bounds leave that side unrestricted, and the operation returns a new expression for use in a query.
Expr.clip(lower_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None, upper_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None) → Expr| Name | Type | Description |
|---|---|---|
lower_bound | NumericLiteral | TemporalLiteral | IntoExprColumn | None = None | Lower boundary; expression inputs are accepted, non-expression inputs are parsed as literals, and None disables the lower limit. |
upper_bound | NumericLiteral | TemporalLiteral | IntoExprColumn | None = None | Upper boundary; expression inputs are accepted, non-expression inputs are parsed as literals, and None disables the upper limit. |
Expr
import polars as pl
df = pl.DataFrame({"a": [-50, 5, 50, None]})
result = df.with_columns(
clipped=pl.col("a").clip(1, 10)
)
print(result)Clips values in column a to the inclusive range 1 through 10 while preserving the null value.
Normalize measurements or scores to a permitted numeric range.
Limit timestamps or durations to an allowed temporal interval.
Apply per-row limits stored in lower and upper columns.
Expr.clip returns an expression that replaces values below the lower bound or above the upper bound with the corresponding boundary. It is applicable to numeric and temporal columns.
Follow-up: How can the bounds vary by row? Pass column expressions as the bounds, for example pl.col("low") and pl.col("up").
Both bounds are optional and default to None. A missing lower bound leaves values below unconstrained, while a missing upper bound leaves values above unconstrained.
Follow-up: How would you apply only an upper limit? Call pl.col("a").clip(upper_bound=10).
Bounds accept expression input, while non-expression inputs are interpreted as literals; strings are interpreted as column names. This lets a clip range be constant or supplied from other columns.
Follow-up: What alternative is recommended for unsupported data types? Build a when-then-otherwise expression.
when