Sub topic 14
The lazy API and query optimization
This chapter assumes you know pandas well, can chain Polars expressions (select, with_columns, filter, group_by().agg()), and have Polars installed (pip install polars). It covers how a LazyFrame differs from a DataFrame, what the optimizer does to your query, and which mistakes cause surprises when porting pandas code.
Eager versus lazy
pandas runs every operation immediately. Each line reads data, allocates a new object, and returns it. Polars offers the same model through DataFrame, which is called the eager API. It also offers a second model through LazyFrame.
A LazyFrame holds a description of a query and no data. Each method you call adds a step to a plan. Nothing runs until you call collect(). Before running, Polars rewrites the plan to do less work.
The rest of the tutorial uses eager code for clarity. For anything that reads files or runs several steps in a row, lazy is usually the better default.
| Aspect | `DataFrame` (eager) | `LazyFrame` (lazy) |
|---|---|---|
| Created by | `pl.read_csv`, `pl.DataFrame` | `pl.scan_csv`, `df.lazy()` |
| Runs when | Each method call | You call `collect()` |
| Optimizer | None across steps | Rewrites the whole plan |
| Inspect data | Print it directly | `collect()` first, or `explain()` for the plan |
Building a lazy query
Use scan_* functions instead of read_* functions. scan_csv, scan_parquet and scan_ndjson return a LazyFrame without loading the file.
import polars as pl
result = (
pl.scan_csv("orders.csv")
.filter(pl.col("qty") > 0)
.group_by("region")
.agg((pl.col("price") * pl.col("qty")).sum().alias("revenue"))
.collect()
)The same expressions work in both APIs, so porting eager code to lazy is usually a matter of changing the entry point and adding collect(). To switch an existing DataFrame, call df.lazy(). To switch back, call collect().
What the optimizer does
The optimizer applies several rewrites. The three that matter most for a migration are:
- Predicate pushdown. A
filteris moved as close to the data source as possible. With Parquet, whole row groups that cannot match are skipped. - Projection pushdown. Only the columns the query uses are read. If a CSV has 40 columns and your query touches 3, the other 37 are not parsed into memory.
- Common subexpression elimination. If the same expression appears several times, it is computed once and reused.
In pandas you would write usecols= and filter early by hand. In lazy Polars, you write the logical query and the optimizer handles the ordering.
The diagram below shows the flow of a lazy query.
Reading the plan with explain
explain() prints the optimized plan without running it. Use it to confirm that pushdown happened.
import polars as pl
lazy = (
pl.scan_csv("orders.csv")
.filter(pl.col("qty") > 0)
.select("region", "price", "qty")
)
print(lazy.explain())
print(lazy.explain(optimized=False))In the optimized output, the filter appears inside the CSV scan node (as a selection) and the scan lists only three columns. In the unoptimized output, the filter and projection sit above a scan that reads everything. Comparing the two is the quickest way to see what the optimizer changed. The exact text varies between Polars versions, so look for the filter and the column list inside the scan rather than matching strings.
Lazy schemas without running
A LazyFrame knows its output schema before any data moves. Use collect_schema() to check the column names and dtypes.
import polars as pl
lazy = pl.scan_csv("orders.csv").with_columns(
(pl.col("price") * pl.col("qty")).alias("total")
)
schema = lazy.collect_schema()
print(schema.names())
print(schema["total"])Use collect_schema() and not the older .columns or .schema attributes on a LazyFrame. Resolving a schema can be costly for complex plans, and newer Polars versions warn about the attribute form.
Common errors when porting
Forgetting to collect
A LazyFrame has no rows to print or index. Printing it shows the plan, not data. Code such as lazy["region"] or len(lazy) fails. Call collect() first, or stay in expressions.
Collecting too early
Calling collect() in the middle of a pipeline and then .lazy() again defeats the optimizer, because the first half runs without knowing what the second half needs. Build the whole query and collect once at the end.
Eager reads followed by `.lazy()`
pl.read_csv("orders.csv").lazy() has already loaded the whole file. Pushdown cannot reduce the read. Use pl.scan_csv so the optimizer sees the source.
Collecting inside loops
Calling collect() repeatedly on queries that share a large scan repeats the read. If you need several results from one source, use pl.collect_all([q1, q2]), which runs the queries together and can share work between them.
import polars as pl
base = pl.scan_csv("orders.csv").filter(pl.col("qty") > 0)
by_region = base.group_by("region").agg(pl.col("qty").sum())
by_day = base.group_by("order_date").agg(pl.col("qty").sum())
region_df, day_df = pl.collect_all([by_region, by_day])Expecting row order after group_by
The optimizer and the parallel engine do not promise a particular group order. Where pandas sorted the group keys by default, Polars does not. Add .sort("region") or pass maintain_order=True to group_by when order matters. The second option is slower, so prefer an explicit sort when you only need stable output.
Side effects in `map_elements`
A Python function passed to map_elements blocks some optimizations and runs row by row. Prefer built-in expressions, as the later chapter on replacing apply explains.
Streaming for data larger than memory
For a file that does not fit in memory, ask Polars to process the query in batches.
import polars as pl
result = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.len().alias("events"))
.collect(engine="streaming")
)The engine="streaming" argument is available in current Polars releases. Older releases used streaming=True. Not every operation supports streaming, and unsupported steps fall back to the in-memory engine, so check your installed version's documentation if memory use stays high. Writing results straight to disk with sink_parquet avoids holding the output in memory too.
import polars as pl
(
pl.scan_csv("orders.csv")
.filter(pl.col("qty") > 0)
.sink_parquet("orders_clean.parquet")
)Choosing eager or lazy
Use lazy when the query reads files, has several steps, or involves large data. Use eager when you are exploring in a notebook and want to see each intermediate result, or when a library needs a concrete DataFrame. A common pattern is to explore eagerly on a sample, then convert the final pipeline to lazy with scan_* and a single collect().
Exercises
Exercise
A colleague wrote pl.read_parquet("big.parquet").lazy().filter(pl.col("year") == 2025).select("id", "amount").collect(). The script still uses a lot of memory. What is wrong, and how do you fix it?
Show answer
read_parquet loads the entire file before .lazy() is called, so predicate and projection pushdown cannot reduce the read. Replace it with pl.scan_parquet("big.parquet"). The optimizer then reads only the id, amount and year columns and skips row groups that cannot contain 2025.
Exercise
You build a LazyFrame q and run q["region"]. It fails. Give two ways to get the column.
Show answer
Call q.collect()["region"] to materialize the data first, or stay lazy with q.select("region").collect(). The second reads less when the query allows projection pushdown.
Exercise
Your pandas code relied on groupby("region") returning sorted keys. After migrating, the output order changes between runs. How do you restore a stable order?
Show answer
Add .sort("region") after the agg. Alternatively use group_by("region", maintain_order=True), which keeps the order in which keys first appear but is slower.