Classify rows
Create a categorical label from numeric or boolean thresholds.
Polars · Function
Starts a conditional expression built from chained when/then branches and an optional otherwise fallback. The first true condition determines the selected value.
pl.when starts a conditional expression. Attach .then for the value selected when its condition matches, optionally chain additional condition/value pairs, and finish with .otherwise; conditions are evaluated in order and the first true branch supplies the result.
polars.when(predicates: IntoExprColumn | Iterable[IntoExprColumn] | bool, **constraints: Any) -> When| Name | Type | Description |
|---|---|---|
predicates | IntoExprColumn | Iterable[IntoExprColumn] | bool | Condition(s) that must be met to apply the subsequent statement; one or more boolean expressions are implicitly combined with &. |
constraints | Any | Keyword equality conditions such as x=123; multiple constraints are implicitly combined with &. |
When
pl.when to begin a conditional Polars expression..then branch is required first, and further branches can be chained..otherwise to define the fallback for rows matching no condition.then value.pl.lit when a branch should produce a string literal.import polars as pl
df = pl.DataFrame({"score": [3, 8, 12]})
result = df.with_columns(
pl.when(pl.col("score") >= 10)
.then(pl.lit("high"))
.when(pl.col("score") >= 5)
.then(pl.lit("medium"))
.otherwise(pl.lit("low"))
.alias("band")
)
print(result)Classifies each score using the first matching condition.
Create a categorical label from numeric or boolean thresholds.
Assign a fallback when no rule matches.
Express column-equality filters directly with keyword arguments.
Build ordered rule systems with multiple predicates.
pl.when select among multiple branches?pl.when begins a conditional expression that is completed with .then, optional chained .when(...).then(...) branches, and optionally .otherwise. The result uses the first condition that evaluates to true.
Follow-up: What happens when every condition is false? The explicitly supplied .otherwise value is returned; without one, the default is None.
pl.when combined?Multiple predicates supplied to pl.when are implicitly combined with logical AND. Keyword constraints such as status="open" express equality conditions and are also combined with AND.
Follow-up: How would you require OR semantics? Build an explicit boolean expression with | inside a predicate rather than passing separate arguments.
Polars evaluates every expression in a when-then-otherwise chain in parallel and filters the results afterward. Therefore, a branch cannot rely on its condition to make an otherwise-invalid expression safe.
Follow-up: How can a literal string be returned reliably? Wrap it with pl.lit, because string inputs to then and otherwise are parsed as column names.
polars.Expr.whenpolars.Expr.thenpolars.Expr.otherwisepolars.litpolars.coalesce