Sub topic 2
Expressions: the building blocks the optimiser can inspect
This chapter assumes you can write basic Python and already use pl.col, select, filter and with_columns. It explains why those expressions matter for lazy queries.
An expression is a description, not a result
A Polars expression describes a computation on columns. It holds no data. pl.col("temp") * 9 / 5 + 32 does not touch any values when you write it. It builds a small tree of operations: a column reference, two constants and three arithmetic steps.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Cairo"],
"temp": [3.0, 19.5, 28.0],
})
to_fahrenheit = (pl.col("temp") * 9 / 5 + 32).alias("temp_f")
print(to_fahrenheit) # prints the description of the computation
print(df.select(to_fahrenheit))The first print shows the expression itself. The second runs it against df. Because the expression is a separate object, you can define it once and apply it to any frame that has a temp column.
Why the optimiser can read expressions
A lazy query is a plan made of steps such as scan, filter and select. Each step carries its expressions. Since an expression is a tree of known operations, the optimiser can answer questions about it:
- Which columns does it read?
- Is it a simple comparison it can move closer to the data source?
- Does the same sub-expression appear twice?
- Can it be rewritten into a cheaper but equivalent form?
Reading the leaves of this tree tells the optimiser that the expression needs only temp. Later chapters build on this: projection pushdown depends on knowing which columns an expression uses, and predicate pushdown depends on knowing that a filter expression only needs columns available at the scan.
Native expressions versus opaque code
The optimiser can only inspect what Polars itself understands. Operations such as pl.col, arithmetic, comparisons, str and dt methods, and aggregations are all visible. A Python function passed to map_elements is not. Polars sees a call to a function and knows nothing about what it does inside.
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3, 4]})
visible = lf.with_columns(y=pl.col("x") * 2)
hidden = lf.with_columns(
y=pl.col("x").map_elements(lambda v: v * 2, return_dtype=pl.Int64)
)
print(visible.collect().equals(hidden.collect()))Both queries produce the same data, so the first line you would check, the result, tells you nothing. The difference is in what the optimiser may do with the plan. Prefer native expressions whenever one exists. A later chapter compares the two plans in detail.
Common errors
- Treating an expression as a value.
pl.col("temp") > 4is not a boolean. Use it insidefilter,selectorwith_columns. - Forgetting
alias. Two expressions on the same column with no alias produce the same output name, and Polars raises a duplicate-column error. - Reaching for
map_elementsfirst. Check whether a built-in expression does the job before writing a Python function.
Exercise
Why can Polars tell that (pl.col("a") + pl.col("b")).alias("c") needs only columns a and b, but cannot tell this for pl.col("a").map_elements(some_function)?
Show answer
The first is a tree of native operations, so the optimiser can read its column references directly. The second hides its logic inside a Python function. Polars sees only that the function is called and cannot inspect what the function does.