Sub topic 3
Expressions: describing a computation on columns
This chapter assumes you can create a DataFrame and read its schema, and that you know basic Python operators and method chaining.
An expression is a recipe, not a result
pl.col("salary") does not fetch any numbers. It creates an expression, which is a description of a computation on a column. Polars runs the description only when you place it inside a context such as select. The next chapter covers contexts in detail.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
expr = pl.col("salary") * 1.1
print(type(expr))
print(df.select(expr))The first print shows an Expr object. The second runs the expression against df and returns a DataFrame. Because an expression is only a description, you can store it in a variable and reuse it on any DataFrame that has a salary column.
Building expressions with operators
Expressions combine with the usual operators. Each operator returns a new expression.
- Arithmetic:
+,-,*,/,//,%,** - Comparison:
==,!=,<,<=,>,>= - Boolean:
&(and),|(or),~(not)
Methods such as .mean(), .sum() and .max() also return expressions, so you can chain them.
out = df.select(
pl.col("name"),
(pl.col("salary") * 1.1).alias("raised"),
(pl.col("salary") >= 90).alias("is_senior"),
((pl.col("dept") == "eng") & (pl.col("salary") > 100)).alias("top_eng"),
(pl.col("salary") - pl.col("salary").mean()).alias("vs_mean"),
)
print(out)The last line shows that one expression can reference a whole column and a single aggregated value. Polars broadcasts the scalar mean across every row.
Output names and independence
An expression takes its output name from its left-most column. So pl.col("salary") * 1.1 produces a column called salary. Use .alias() to give it a new name. If two expressions in one select produce the same name, Polars raises a duplicate-name error.
Expressions in the same context are independent. They all read the input DataFrame, and none can see a column created by another expression in the same call. To use a new column, create it in one with_columns call and read it in the next.
step = (
df.with_columns((pl.col("salary") * 1.1).alias("raised"))
.with_columns((pl.col("raised") - pl.col("salary")).alias("gain"))
)
print(step)Common errors
- Missing parentheses. In Python,
&binds more tightly than==and>=. Write(a > 1) & (b == 2), nota > 1 & b == 2. - Using
and,ororif. Python tries to turn an expression into a single True or False value, which is ambiguous for a column, so Polars raises an error. Use&,|andwhen/then/otherwise. - Expecting a value outside a context.
pl.col("salary") * 2alone is never evaluated. Pass it toselect,with_columnsorfilter. - Forgetting
alias. The result silently keeps the source column's name, which can overwrite a column inwith_columns.
Exercise
Why does df.filter(pl.col("salary") > 90 & pl.col("dept") == "eng") fail, and how do you fix it?
Show answer
& has higher precedence than > and ==, so Python evaluates 90 & pl.col("dept") first, which is not a valid comparison. Wrap each comparison in parentheses: df.filter((pl.col("salary") > 90) & (pl.col("dept") == "eng")).