Sub topic 6
Conditional columns with when/then/otherwise
This chapter assumes you can already write expressions with pl.col and use select, with_columns and filter. It covers the Polars way to build a column whose value depends on a condition, and the mistakes that usually come with it.
The shape of a conditional expression
A conditional expression has three parts: pl.when(condition), .then(value) and .otherwise(value). It is an ordinary expression, so you can use it in any context. It is not an if statement. Polars evaluates the condition for the whole column at once and picks a value per row.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
df2 = df.with_columns(
pl.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band")
)
print(df2)Ana and Ben get "high". Cy and Dee get "standard". The other columns are unchanged, because with_columns keeps them.
Strings in then and otherwise are column names
Polars parses a bare string passed to then or otherwise as a column name, the same way it does in select. This code fails with a column-not-found error, because Polars looks for columns called high and standard:
# Raises ColumnNotFoundError: there is no column named "high"
df.with_columns(
pl.when(pl.col("salary") >= 100).then("high").otherwise("standard").alias("band")
)Wrap literal values in pl.lit(...). Numbers and booleans are usually fine without it, but using pl.lit for every literal is a safe habit. Use pl.col(...) when you want values from a column:
adjusted = df.with_columns(
pl.when(pl.col("dept") == "eng")
.then(pl.col("salary") * 1.1)
.otherwise(pl.col("salary"))
.alias("adjusted")
)
print(adjusted)The then branch is a float and the otherwise branch is an integer. Polars finds a common type, here Float64, and the result column has that type. If no common type exists, such as a string with an integer, you get an error. Cast one branch explicitly in that case.
Combining conditions
Python's and, or and not do not work on expressions. Use &, | and ~, and put each comparison in parentheses. Without parentheses, & binds more tightly than >=, and the expression fails or means something else.
flagged = df.with_columns(
pl.when((pl.col("dept") == "ops") & (pl.col("salary") < 90))
.then(pl.lit("review"))
.otherwise(pl.lit("ok"))
.alias("flag")
)
print(flagged)when also accepts several predicates, and they are combined with AND. These two forms mean the same thing:
cond_a = pl.col("dept") == "ops"
cond_b = pl.col("salary") < 90
one = pl.when(cond_a & cond_b).then(pl.lit(1)).otherwise(pl.lit(0))
two = pl.when(cond_a, cond_b).then(pl.lit(1)).otherwise(pl.lit(0))For membership tests, is_in is shorter than a chain of |. For range tests, is_between is shorter than two comparisons:
checked = df.with_columns(
pl.when(pl.col("dept").is_in(["eng", "sales"]))
.then(pl.lit("tech"))
.otherwise(pl.lit("other"))
.alias("area"),
pl.col("salary").is_between(85, 110).alias("mid_range"),
)
print(checked)Chaining several branches
Add more .when(...).then(...) pairs before the final .otherwise(...). Branches are checked in order, and the first true condition wins for each row. This works like if / elif / else, so put the most specific condition first.
tiers = df.with_columns(
pl.when(pl.col("salary") >= 110)
.then(pl.lit("senior"))
.when(pl.col("salary") >= 95)
.then(pl.lit("mid"))
.otherwise(pl.lit("junior"))
.alias("tier")
)
print(tiers)Ana is senior, Ben is mid, and Cy and Dee are junior. If you reversed the two conditions, Ana would be mid, because 120 is also at least 95.
What happens without otherwise
If you leave out .otherwise(...), rows that match no branch get null. This is useful when you want a column that is only filled in for some rows:
bonus = df.with_columns(
pl.when(pl.col("dept") == "eng").then(pl.col("salary") * 0.1).alias("bonus")
)
print(bonus)The bonus column is 12.0 and 10.0 for the engineers, and null for the ops rows.
Null conditions fall through
A condition that evaluates to null is not true, so the row falls through to the next branch or to otherwise. Comparisons with a null value produce null, not false. This is the most common source of wrong results in conditional columns.
people = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"salary": [120, 100, None, 90],
}
)
wrong = people.with_columns(
pl.when(pl.col("salary") >= 110)
.then(pl.lit("senior"))
.when(pl.col("salary") >= 95)
.then(pl.lit("mid"))
.otherwise(pl.lit("junior"))
.alias("tier")
)
print(wrong)Cy has no salary, but the result says junior. The comparisons gave null, and otherwise caught the row. Make the null case an explicit first branch:
right = people.with_columns(
pl.when(pl.col("salary").is_null())
.then(pl.lit("unknown"))
.when(pl.col("salary") >= 110)
.then(pl.lit("senior"))
.when(pl.col("salary") >= 95)
.then(pl.lit("mid"))
.otherwise(pl.lit("junior"))
.alias("tier")
)
print(right)Now Cy is unknown. The next chapter on null handling covers fill_null and related tools in more detail.
Conditionals inside aggregations and filters
A when expression is a normal expression, so you can use it inside group_by and agg. A when without otherwise returns null for non-matching rows, and most aggregations skip nulls. That gives you a conditional aggregate:
summary = (
df.group_by("dept")
.agg(
pl.when(pl.col("salary") >= 100)
.then(pl.col("salary"))
.mean()
.alias("avg_high"),
pl.when(pl.col("salary") >= 100)
.then(pl.lit(1))
.otherwise(pl.lit(0))
.sum()
.alias("n_high"),
)
.sort("dept")
)
print(summary)The eng group has an avg_high of 110.0 and an n_high of 2. The ops group has no matching rows, so its avg_high is null and its n_high is 0. For a plain count, (pl.col("salary") >= 100).sum() gives the same result in less code, because booleans sum as 0 and 1.
Performance and evaluation notes
- A conditional expression runs inside Polars' native engine. It is much faster than
map_elementswith a Pythonif, which calls Python once per row. - Polars does not short-circuit. It computes the
thenandotherwiseexpressions for all rows, then selects per row. An expression in an unused branch can still be evaluated, so do not rely on awhento guard against invalid input in another branch. - For a mapping from a few fixed values to other values, such as
"eng"to3,replaceor a join against a small lookup table is often clearer than a long chain ofwhen.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ColumnNotFoundError` naming your literal | A bare string in `then` or `otherwise` is a column name | Use `pl.lit("text")` | |
| Error mentioning `ambiguous` truth value | `and`, `or` or `not` used on expressions | Use `&`, `\ | ` and `~` |
| Wrong results or an operator error in a combined condition | Missing parentheses around comparisons | Parenthesize each comparison | |
| Unexpected `null` column values | No `otherwise` and no branch matched | Add `.otherwise(...)` or accept the nulls | |
| Null rows land in the default branch | Null condition counts as not true | Add an `is_null()` branch first | |
| Type error between branches | No common type, such as string and integer | Cast one branch with `.cast(...)` |
Exercise
Using the people DataFrame above (salaries 120, 100, null, 90), write an expression that adds a column raise_pct with 10.0 for salaries of at least 100, 5.0 for other known salaries, and null for missing salaries. Which branch order do you need, and do you need otherwise?
Show answer
pl.when(pl.col("salary").isnull()).then(pl.lit(None)).when(pl.col("salary") >= 100).then(pl.lit(10.0)).otherwise(pl.lit(5.0)).alias("raisepct"). Putting the null branch first matters, because a null salary would otherwise fall through to otherwise and get 5.0. You do need otherwise for the 5.0 case. A simpler form drops the null branch and uses pl.when(pl.col("salary") >= 100).then(10.0).when(pl.col("salary") < 100).then(5.0) with no otherwise. Null salaries match neither condition, so they stay null.
Exercise
A teammate writes pl.when(pl.col("dept") == "ops" and pl.col("salary") < 90).then("review").otherwise("ok"). Name the two problems and give the corrected expression.
Show answer
First, and cannot combine expressions, so Python raises an error about an ambiguous truth value. Use & with each comparison in parentheses. Second, "review" and "ok" are bare strings, which Polars reads as column names. Wrap them in pl.lit. The fixed version is pl.when((pl.col("dept") == "ops") & (pl.col("salary") < 90)).then(pl.lit("review")).otherwise(pl.lit("ok")).