Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Expressions

When, Then, Otherwise

Create conditional columns in Polars with when, then and otherwise: chained branches, multiple conditions, null handling, cut and bucketing, and replace_strict mapping.

"If this, then that, otherwise something else" is the most common piece of data logic: grade a score, flag large orders, label a temperature. In Python you would write if statements in a loop. In Polars you write a conditional expression with pl.when(...).then(...).otherwise(...), and it runs on the whole column at once.

The basic shape

Python when / then / otherwise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read it as a sentence: when score is at least 60, then "pass", otherwise "fail". Both branches are expressions, so they may be columns or computations, not only constants. A plain Python string in then is treated as a column name in some versions, so wrap literal text in pl.lit(...) to be safe.

Chaining several branches

Add more when(...).then(...) pairs before otherwise. The first matching condition wins, like if / elif / else.

Python Grades with several branches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Order matters: because the first true condition wins, test the strictest condition (>= 90) first.

Computing values in the branches

Python Branch values from columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If you leave out otherwise, rows that match no condition become null. That is sometimes exactly what you want (a flag only for special rows) and sometimes a bug, so be deliberate.

Combining conditions

Use &, | and ~ inside when, with parentheses around each comparison.

Python Compound conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Nulls in conditions

If the condition is null for a row, the row falls through to the next branch or to otherwise, because null is not true. Test for missing values first when you care about them.

Python Handling nulls explicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without the first line, the missing temperature would be labelled "mild", which is silently wrong.

Replacing values: replace_strict and replace

For a lookup of exact values to other values, a mapping is shorter than a ladder of whens.

Python Mapping codes to labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

replace_strict maps every value (using default for unmatched ones, or raising an error if you give none). replace changes only the listed values and keeps the others, without changing the type.

Binning numbers: cut and friends

To bucket a number into ranges, cut and qcut are built for it, and search_sorted-style logic is not needed.

Python Binning with cut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

cut(breaks, labels=...) makes intervals that include the right edge: breaks [17, 64] give (-inf, 17], (17, 64], (64, inf). There is one more label than breaks. qcut cuts by quantiles, giving groups of roughly equal size.

Compare with the alternatives

Need Best tool
Two or three rules on different columns when/then/otherwise
Map exact values to other values replace_strict
Bucket a number into ranges cut or qcut
Clamp a number to a range clip
Pick the first non-null pl.coalesce

Avoid map_elements with a Python if function. A when/then/otherwise expression does the same job in compiled code, in parallel, and works in lazy mode too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a when/then chain with no otherwise return for rows that match no condition?

    Without otherwise, unmatched rows get null. Add otherwise when you need a default value.
  2. 2. In a chain of when(...).then(...) branches, which branch is used if several conditions are true?

    Branches are checked in order and the first true condition wins, like if/elif/else.
  3. 3. Which is the right tool to turn the codes 'N','S','E','W' into full direction names?

    replace_strict maps exact values to new values and can supply a default for unmatched ones.
  4. 4. With breaks [17, 64] and three labels, which band does age 64 fall in?

    cut intervals include their right edge by default, so 64 belongs to the middle band (17, 64].

Summary

  • pl.when(cond).then(a).otherwise(b) is a vectorized if/else; chain whens for elif.
  • Branch values can be any expressions; omitting otherwise yields null.
  • Handle null conditions first, because null conditions fall through.
  • Use replace_strict, cut, qcut, clip and coalesce for common patterns.

Next: Column Selectors