Sub topic 16
Running These Operations Lazily
This chapter assumes you can write group_by, join, and over expressions on a DataFrame, and that you know what a column expression such as pl.col("sales").sum() is. Here you will run the same operations on a LazyFrame. You will also learn what the optimizer does with them, and which mistakes come from moving between the two modes.
Eager and lazy: the same expressions, a different timing
An eager DataFrame runs each call immediately and returns a result. A LazyFrame only records the call. Nothing runs until you call collect(). At that point Polars looks at the whole recorded query, rewrites it into a cheaper form, and then executes it.
The expressions you wrote in the earlier chapters work unchanged. agg, over, join_asof, and group_by_dynamic exist on LazyFrame with the same arguments. Only the entry and exit points change:
df.lazy()converts aDataFrameto aLazyFrame.pl.LazyFrame({...})builds one directly from data.pl.scan_csv(...)andpl.scan_parquet(...)read files lazily.lf.collect()runs the plan and returns aDataFrame.
A grouping and joining pipeline
The next query joins orders to customers, keeps large orders, and totals them per customer name. It uses the data from the join chapter.
import polars as pl
customers = pl.LazyFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
})
orders = pl.LazyFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 1, 4],
"amount": [30, 20, 50],
})
plan = (
orders.join(customers, on="customer_id", how="left")
.filter(pl.col("amount") > 25)
.group_by("name")
.agg(pl.col("amount").sum().alias("total"))
.sort("name")
)
print(plan.explain())
print(plan.collect())
# Ana: total 30; the unmatched order 102 forms a null group with total 50.
# Nulls sort first by default, so the null row comes before Ana.explain() prints the optimized plan as text without running it. The exact wording depends on your Polars version. In the plan, the amount > 25 filter normally sits below the join, next to the scan of orders. This is predicate pushdown. The optimizer can do this because amount comes from the left table, so filtering early gives the same result and joins fewer rows. Use explain(optimized=False) to see the plan as you wrote it.
What the optimizer does for these operations
| Optimization | What it does | Where you see it |
|---|---|---|
| Predicate pushdown | Moves filters as close to the data source as is safe | A filter after a join runs before it |
| Projection pushdown | Reads only the columns the query uses | `scan_parquet` skips unused columns |
| Common subplan elimination | Computes a repeated sub-query once | Self-joins on the same filtered source |
| Slice pushdown | Stops early when only the first rows are needed | `head(5)` after a scan |
Projection pushdown matters for group_by and join. If a table has 50 columns and your query touches 4, the other 46 are never loaded from a Parquet file.
Windows and filters: order still matters
The optimizer must preserve meaning. A filter placed after over cannot be moved before it, because removing rows first would change what each group contains. The two queries below return different answers, and lazy mode keeps them different.
sales = pl.LazyFrame({
"region": ["east", "east", "west", "west", "west"],
"product": ["a", "b", "a", "b", "b"],
"sales": [10, 20, 5, 15, 25],
})
total = pl.col("sales").sum().over("region").alias("region_total")
after = sales.with_columns(total).filter(pl.col("product") == "b")
before = sales.filter(pl.col("product") == "b").with_columns(total)
print(after.collect()) # region_total: east 30, west 45, west 45
print(before.collect()) # region_total: east 20, west 40, west 40In after, the totals include every product in the region. In before, only product b rows are summed. Whichever order you write is the one you get. Lazy mode changes how fast the query runs, not which rows it returns.
Ordered operations: sort first
rolling_mean, group_by_dynamic, and join_asof all depend on row order. A lazy plan does not sort for you. For group_by_dynamic and join_asof, put an explicit sort on the key column before the call.
from datetime import datetime
events = pl.LazyFrame({
"ts": [datetime(2026, 1, 2, 10), datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 15)],
"value": [3, 1, 2],
})
daily = (
events.sort("ts")
.group_by_dynamic("ts", every="1d")
.agg(pl.col("value").sum().alias("daily_total"))
)
print(daily.collect()) # 2026-01-01: 3; 2026-01-02: 3The rows here start out of order on purpose. Without the sort, the bucketing may fail or return wrong buckets, depending on the version. Polars can warn about unsorted data, but you should not rely on it. The same rule applies to join_asof: sort both tables on the join key first.
Group order follows the same logic. A lazy group_by makes no promise about the order of the output groups, just like the eager version. Either add a sort after the aggregation or pass maintain_order=True. The second option costs some speed and can limit optimizations, so prefer sort when you only need a deterministic output.
Common errors
- Forgetting
collect(). Printing aLazyFrameshows the plan, not the data. If you seenaive planorFILTER,JOIN,AGGREGATEoperators in your output, you have not collected. - Late errors. Calling
.select("misspelled")on aLazyFrameusually does not fail where you wrote it. The error appears atcollect()orcollect_schema(), and the traceback points at the collect call. When debugging, callcollect_schema()after each step to find the first step that breaks. - Calling
collect()many times on the same plan. Each call re-runs the whole query, including the scan. Collect once and keep theDataFrame, or usepl.collect_all([plan_a, plan_b])so Polars can share common work. - Mixing frame types in a join.
LazyFrame.joinexpects anotherLazyFrame. If one side is aDataFrame, call.lazy()on it first. - Expecting row-by-row debugging. You cannot inspect a value mid-chain. Use
explain()for the plan, orcollect()a smaller prefix withhead()to check a step.
When to stay eager
Lazy mode is not always better. For small in-memory data, the optimizer saves little. Eager code is also simpler to step through in a notebook. Lazy mode pays off when:
- the source is a file and you only need some columns or rows,
- the query has several joins and filters whose best order is not obvious,
- the result is larger than memory and you want to try the streaming engine, for example
plan.collect(engine="streaming")on recent versions. Not every operation supports streaming, and Polars falls back or raises depending on the version, so check your version's documentation.
A practical habit is to prototype eagerly on a sample, then change DataFrame to LazyFrame and add one collect() at the end.
Exercise
A lazy query joins orders to customers with a left join, then filters on pl.col("name") == "Ana" (a column from the right table), then groups by name. A colleague says the filter will always be moved below the join by predicate pushdown. Is that right, and how would you check?
Show answer
No. A filter on a right-table column after a left join also removes the unmatched left rows, so moving it below the join would change the result. The optimizer only moves a filter when the result stays the same, so you cannot assume it moves. Check by calling plan.explain() and looking at where the filter appears relative to the join. If you want the filter applied before the join, write customers.filter(pl.col("name") == "Ana") yourself and join the filtered table. That changes the meaning to match what you want, which may be an inner join rather than a left join.
Exercise
You write sales.with_columns(pl.col("sales").sum().over("region").alias("t")).filter(pl.col("product") == "b") on a LazyFrame, but you wanted each total to count only product b. What do you change?
Show answer
Move the filter before with_columns: sales.filter(pl.col("product") == "b").with_columns(pl.col("sales").sum().over("region").alias("t")). Alternatively keep one pass and use a filtered expression, pl.col("sales").filter(pl.col("product") == "b").sum().over("region"), which keeps all rows but sums only product b values. The optimizer keeps the order you write, so the order of the calls decides the result.