Sub topic 16
Running these operations lazily
This chapter assumes you can write group_by/agg, joins, and over expressions on a DataFrame, as covered earlier. It shows how to run the same code lazily.
Eager and lazy
An eager DataFrame runs each step as soon as you call it. A LazyFrame only records the steps as a query plan. Nothing runs until you call collect(). Because Polars sees the whole plan first, it can optimize it before running it.
You can get a LazyFrame in three ways:
- Call
.lazy()on a DataFrame. - Build one directly with
pl.LazyFrame(...). - Read a file with
pl.scan_csvorpl.scan_parquet.
The expressions you pass to group_by, join, and over are the same in both modes.
import polars as pl
orders = pl.LazyFrame({
"order_id": [100, 101, 102, 103],
"customer_id": [1, 1, 2, 4],
"amount": [30, 20, 50, 10],
})
customers = pl.LazyFrame({
"customer_id": [1, 2, 3],
"region": ["east", "west", "west"],
})
plan = (
orders.join(customers, on="customer_id", how="left")
.filter(pl.col("customer_id") < 4)
.group_by("region")
.agg(
pl.col("amount").sum().alias("total"),
pl.len().alias("orders"),
)
.sort("region")
)
print(plan.explain())
print(plan.collect()) # east: total 50, orders 2; west: total 50, orders 1explain() returns the optimized plan as text, so you can check what Polars will do without running it. Printing plan itself shows only the plan, not data.
What the optimizer does
The optimizer rewrites the plan without changing the result. The main rewrites are:
- Predicate pushdown moves a
filteras early as it can. In the example, the filter oncustomer_idcan be applied toordersbefore the join, so the join handles fewer rows. - Projection pushdown reads only the columns the query needs. With
scan_parquet, unused columns are never loaded. - Common subplan elimination computes a repeated subquery once.
Window expressions and filters
A filter is not always moved ahead of a window expression. Take this plan:
share = (
orders.join(customers, on="customer_id", how="left")
.with_columns(
(pl.col("amount") / pl.col("amount").sum().over("region")).alias("share")
)
.filter(pl.col("amount") > 15)
)
print(share.collect())The share column is computed from every row in each region, including the small orders. If the optimizer applied the filter first, the region totals would change. Polars keeps the result identical to the eager version, so you don't have to reason about this yourself. It does mean that filtering before over is a real choice that changes your numbers. Write that filter explicitly if it's what you want.
Common errors
- Forgetting
collect(). You get a plan, not rows. Calling.head()on aLazyFrameis also lazy. - Unsorted inputs.
group_by_dynamicandjoin_asofneed the key column sorted. Lazy mode doesn't sort it for you. - Assuming group order.
group_byoutput order is still not guaranteed. Usesortormaintain_order=True. - Inspecting columns. Use
collect_schema()to see column names and types without running the query.
Exercise
You write pl.scan_parquet("sales.parquet").group_by("region").agg(pl.col("amount").sum()) and print the result. You see a query plan instead of rows. What is missing, and what does the optimizer do with the file's other columns?
Show answer
You need to call .collect() at the end, because a LazyFrame only records the plan. With projection pushdown, Polars reads only the region and amount columns from the Parquet file and skips the rest.