Sub topic 3
Expressions: describing a computation on columns
This chapter assumes you can run Python with Polars installed, and that you know what a DataFrame and a Series are (the previous chapters cover both). It also assumes you have seen method chaining. You do not need to know the contexts (select, with_columns, filter) in detail. The next chapter covers them, and here they only serve as places to run expressions.
What an expression is
An expression is a description of a computation on one or more columns. Building one does not touch any data. It records what you want, and Polars runs it later, when you hand it to a DataFrame method.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
"bonus": [10, 5, 0, 8],
}
)
double = pl.col("salary") * 2
print(type(double))
print(df.select(double))pl.col("salary") is not a column of values. It is an expression that means "the column named salary". Multiplying it by 2 produces a new, larger expression. double is an Expr object, and the select call is what produces data: a one-column DataFrame holding 240, 200, 160 and 180.
This split has three consequences:
- An expression is not bound to one DataFrame. You can define it once and use it on any DataFrame that has a
salarycolumn. - Polars sees the whole computation before running it. That lets it run independent expressions in parallel and, in the lazy API, optimize the plan.
- Expressions work on whole columns, never on one row at a time. You write "salary times two", not a loop over rows.
Building expressions
Referring to columns and literals
pl.col("name") refers to a column. pl.lit(value) creates a constant. In most arithmetic and comparisons Polars wraps plain Python values for you, so pl.col("salary") * 2 works without pl.lit(2). You need pl.lit when a constant stands alone, for example as the value in then(...) or as a whole output column.
print(
df.select(
pl.col("name"),
pl.lit("2026").alias("year"),
)
)The literal is repeated for every row, so year holds "2026" four times.
Arithmetic, comparison and boolean operators
Expressions support the usual Python operators. Arithmetic (+ - * / // % **) returns a numeric expression. Comparisons (== != < <= > >=) return a boolean expression. Boolean expressions combine with & (and), | (or), ~ (not) and ^ (xor).
total = pl.col("salary") + pl.col("bonus")
senior_eng = (pl.col("salary") >= 90) & (pl.col("dept") == "eng")
print(df.select(total.alias("total")))
print(df.filter(senior_eng))The first call returns 130, 105, 80 and 98. The second keeps Ana and Ben.
Two details cause most beginner errors here:
- Use
&,|and~, notand,orandnot. Python's keywords try to turn the expression into a single True or False, and Polars raises an error saying the truth value of an expression is ambiguous. - Put each comparison in parentheses. In Python,
&binds tighter than>=and==, sopl.col("salary") >= 90 & pl.col("dept") == "eng"does not mean what it appears to.
Methods on expressions
Most of the work happens in methods you chain onto an expression. Each call returns a new expression.
expr = (
pl.col("salary")
.cast(pl.Float64)
.sqrt()
.round(2)
.alias("salary_root")
)
print(df.select(expr))Methods are grouped by data type. Numeric methods sit on the expression itself, and other types use namespaces such as .str and .dt, which a later chapter covers.
Output names
Every expression produces a column with a name, and the rules decide what you see in the result:
pl.col("salary") * 2keeps the namesalary.- A binary operation such as
pl.col("salary") + pl.col("bonus")takes the name of the left-most column, heresalary. This is why the earliertotalexpression needed.alias("total")to get a meaningful name. - A literal on its own is named
literalunless you alias it. .alias(name)sets the name explicitly.
Names matter because a DataFrame cannot hold two columns with the same name. This call fails with a duplicate-name error:
# Raises polars.exceptions.DuplicateError: both outputs are named "salary"
df.select(pl.col("salary"), pl.col("salary") * 2)The fix is to alias one of them:
print(df.select(pl.col("salary"), (pl.col("salary") * 2).alias("double")))A good habit is to call .alias on every derived column, even when the default name would be unique. The intent is then visible in the code.
Expressions that produce several columns
One expression can expand into several output columns. Give pl.col more than one name, and the rest of the expression applies to each.
print(df.select(pl.col("salary", "bonus") * 2))
print(df.select(pl.col("salary", "bonus").sum()))The first call returns two columns, salary and bonus, each doubled. The second returns one row with salary equal to 390 and bonus equal to 23. pl.all() expands to every column, and pl.col(pl.Int64) expands to every column with that data type. A later chapter covers selecting many columns in depth.
Expanded outputs keep their own input names, so you do not hit the duplicate-name problem. To rename them in bulk, use the .name namespace, for example .name.suffix("_x2").
Lengths: columns, scalars and broadcasting
An expression's result is either a column with as many values as the input, or a single value (a scalar). Aggregations such as sum, mean, min, max and n_unique return scalars. When a context combines a scalar with full-length columns, Polars broadcasts the scalar, which means it repeats the value for each row.
print(
df.select(
pl.col("name"),
pl.col("salary"),
pl.col("salary").mean().alias("avg"),
)
)The avg column is 97.5 in every row. The same rule makes this expression valid, because the mean broadcasts against the column:
above_avg = pl.col("salary") > pl.col("salary").mean()
print(df.filter(above_avg))This keeps Ana (120) and Ben (100). Broadcasting only works for length one. If a context receives columns of different lengths, and none has length one, Polars raises a shape error.
Reusing expressions
Because expressions are ordinary Python values, you can store them, pass them to functions and return them from functions. This is the main way to avoid repeating logic.
def pct_of_total(column: str) -> pl.Expr:
return (pl.col(column) / pl.col(column).sum() * 100).alias(f"{column}_pct")
print(df.select(pl.col("name"), pct_of_total("salary"), pct_of_total("bonus")))The function returns a description. Nothing runs until select receives it. Annotating the return type as pl.Expr helps editors and readers.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Error about an ambiguous truth value | Used `and`, `or` or `not` with expressions | Use `&`, `\ | `, `~` |
| Filter returns wrong rows or raises a type error | Missing parentheses around comparisons | Wrap every comparison in parentheses | |
| `DuplicateError` on output | Two outputs share a name | Add `.alias(...)` | |
| `ColumnNotFoundError` | Name misspelled, or column not yet created in this context | Check `df.columns`, and create the column in an earlier step | |
| Printing an expression shows a description, not numbers | An expression is not data | Pass it to a context, such as `df.select(expr)` | |
| `col == None` gives no useful result | Comparing to null gives null | Use `.is_null()` |
Summary of the working model
- An expression describes a computation. A context runs it.
- Operators and methods return new expressions, so they chain.
- Each output has a name, taken from the left-most input unless you alias it.
- A result is a full column or a scalar, and scalars broadcast.
- Expressions are plain Python objects, so wrap repeated logic in functions that return
pl.Expr.
Exercise
Given the DataFrame df from this chapter, write one select call that returns a column named "bonusshare" holding each person's bonus as a fraction of the department's total bonus is not yet possible without grouping, so instead write one select that returns two columns: "totalcomp" (salary plus bonus) and "above_avg" (True where salary is greater than the mean salary). Explain why both expressions need an alias or a check on their names.
Show answer
df.select((pl.col("salary") + pl.col("bonus")).alias("totalcomp"), (pl.col("salary") > pl.col("salary").mean()).alias("aboveavg")). Both expressions would otherwise take the name "salary", because the output name comes from the left-most column, and a DataFrame cannot have two columns with the same name. The mean is a scalar, so it broadcasts against the full salary column in the comparison.
Exercise
Why does df.filter(pl.col("salary") >= 90 and pl.col("dept") == "eng") fail, and how do you write it correctly?
Show answer
The Python keyword and tries to convert an expression to a single True or False, which Polars refuses because the value is ambiguous. Write df.filter((pl.col("salary") >= 90) & (pl.col("dept") == "eng")), with & and with parentheses around each comparison.