Sub topic 6
Conditional columns with when/then/otherwise
This chapter assumes you can write select and with_columns expressions with pl.col, and that you know how comparison and boolean operators combine columns. Here you will build columns whose values depend on a condition, which is the Polars counterpart of SQL's CASE WHEN or pandas' np.where.
The basic form
A conditional expression has three parts. pl.when() takes a boolean expression. .then() gives the value for rows where it is true. .otherwise() gives the value for all other rows. The whole chain is a single expression, so you place it inside a context such as with_columns and name the result with alias.
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. Use pl.lit for constant values so Polars treats them as literal values, not column names.
Chaining branches and combining conditions
You can add more .when().then() pairs before .otherwise(). Polars checks them in order, and each row takes the value of the first branch that matches. To combine tests inside one when, use & (and), | (or) and ~ (not). Wrap each comparison in parentheses, because these operators bind more tightly than >= or ==.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
result = df.with_columns(
pl.when(pl.col("salary") >= 110)
.then(pl.lit("senior"))
.when(pl.col("salary") >= 90)
.then(pl.lit("mid"))
.otherwise(pl.lit("junior"))
.alias("level"),
pl.when((pl.col("dept") == "ops") & (pl.col("salary") < 90))
.then(pl.col("salary") * 1.1)
.otherwise(pl.col("salary"))
.alias("adjusted"),
)
print(result)The level column is senior, mid, junior, mid. The second expression shows that then and otherwise accept any expression, not only literals. Here it raises pay by 10% for low-paid ops staff and leaves everyone else unchanged.
Common errors
- Missing
otherwise. Rows that match no branch become null. This is sometimes what you want, but it often surprises people. - Null in the condition. A null test result is not true, so the row falls through to the next branch or to
otherwise. If nulls need their own treatment, test for them first withpl.col("x").is_null(). - Mismatched types. Branch values should share a compatible type, such as int and float. Mixing text with numbers raises an error or gives an unexpected type. Check the result with
df.schema. - Missing parentheses. Writing
pl.col("a") == 1 & pl.col("b") == 2fails or gives wrong results. Parenthesize each comparison.
Exercise
Using the df from this chapter, write a with_columns call that adds a column "flag". It should be "eng-high" for rows where dept is "eng" and salary is at least 110, "other" for every other row. What are the values for Ana, Ben, Cy and Dee?
Show answer
Use pl.when((pl.col("dept") == "eng") & (pl.col("salary") >= 110)).then(pl.lit("eng-high")).otherwise(pl.lit("other")).alias("flag"). The values are "eng-high" for Ana and "other" for Ben, Cy and Dee. Ben is in eng but earns 100, which is below 110.