Sub topic 14
The lazy API and query optimization
This chapter assumes you can write Polars expressions, use filter, group_by and agg, and have read CSV files with pandas. It covers how a lazy query differs from the eager code you have written so far.
Eager versus lazy
pandas runs every step as soon as you call it. Polars has two modes. A DataFrame is eager and runs each step immediately. A LazyFrame records the steps as a query plan and runs nothing until you call collect().
Because Polars sees the whole query before it runs, it can reorder and trim the work. A pandas script that loads a file, then filters, then selects columns has no such option.
Your first lazy query
Replace read_csv with scan_csv, and end the chain with collect().
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()
)scan_csv reads nothing yet. filter, group_by and agg add steps to the plan. collect() optimizes the plan, runs it and returns an ordinary DataFrame.
What the optimizer does
- Predicate pushdown moves filters as close to the file read as possible, so rows that fail the filter are discarded early.
- Projection pushdown reads only the columns the query uses. Here,
orders.csvis read forregion,priceandqtyonly. - Common subplan elimination computes a repeated sub-query once.
You do not request these. They apply automatically.
Inspecting the plan
Call explain() on a LazyFrame to see the optimized plan without running it.
query = (
pl.scan_csv("orders.csv")
.filter(pl.col("qty") > 0)
.select("region", "price", "qty")
)
print(query.explain())In the output, the filter and the column list appear inside the scan node. That shows the pushdown happened.
Moving between modes
df.lazy()turns an eagerDataFrameinto aLazyFrame.lf.collect()turns aLazyFrameinto aDataFrame.
Writing pl.read_csv("orders.csv").lazy() works, but it loads the whole file first. Use scan_* functions (scan_csv, scan_parquet) so the optimizer can limit the read.
Common errors
- Forgetting
collect(). Printing a LazyFrame shows the plan, not data. Addcollect()to get rows. - Inspecting data mid-chain. A LazyFrame has no rows to show. Use
lf.head(5).collect()to preview. - Collecting too early. Calling
collect()in the middle of a pipeline and continuing eagerly throws away optimization. Collect once, at the end. - Expecting column access.
lf["price"]does not work. Uself.select("price").
Migration advice
Write new pipelines lazily from the start, with scan_* as the entry point. Convert existing eager code by changing the reader and adding one collect() at the end. For small data the speed gain is minor. For large files, the reduced reading is where the gain comes from.
Exercise
A script calls pl.read_csv("big.csv").filter(pl.col("year") == 2024).select("id", "amount"). How would you change it so Polars reads only the needed rows and columns, and what must you add at the end?
Show answer
Replace readcsv with scancsv and keep the filter and select. The optimizer then pushes the filter and the column selection into the file read. Finish the chain with .collect(), because a LazyFrame runs nothing until collected.