Sub topic 13
The lazy API: lazy frames and collect
This chapter assumes you can write expressions and use select, with_columns, filter and group_by on a DataFrame. It also assumes you know basic Python method chaining.
Eager versus lazy
A DataFrame is eager. Each method runs immediately and returns a new DataFrame. A LazyFrame is lazy. Each method adds a step to a query plan, and nothing runs until you call collect().
The lazy API uses the same expressions and contexts you already know. What changes is when the work happens. Because Polars sees the whole query before running it, it can reorder and trim steps.
Building a lazy query
You can start lazy by scanning a file, or switch an existing DataFrame with lazy(). The example below assumes a sales.csv file with region and amount columns.
import polars as pl
lazy_result = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(lazy_result.explain())
print(lazy_result.collect())scan_csv does not load the file. It records where the data lives. filter and group_by add steps to the plan. explain() returns the plan as text, and collect() runs it and returns a normal DataFrame.
import polars as pl
df = pl.DataFrame({"dept": ["eng", "ops"], "salary": [120, 80]})
lf = df.lazy()
print(type(lf))
print(lf.with_columns((pl.col("salary") / 12).alias("monthly")).collect())Why lazy can be faster
Because the plan is known in advance, Polars can optimize it. Two common optimizations are:
- Predicate pushdown: a
filtermoves as close to the data source as possible, so fewer rows are read. - Projection pushdown: only the columns the query uses are read from the file.
The diagram shows the flow from your code to a result.
Reading the plan
Call explain() to see what Polars will do. Read it from the bottom up. The bottom line is the data source, and each line above it is a later step. If predicate pushdown applied, the filter appears inside the scan line instead of as a separate step. The next chapters cover plans in more detail.
Common errors
- Forgetting
collect(). Printing a LazyFrame shows its plan, not data. Add.collect()to get rows. - Calling DataFrame-only methods on a LazyFrame. Methods that need data to exist right now, such as indexing with
df[0, "name"], are not available. Collect first. - Collecting too early. If you call
collect()in the middle of a pipeline and continue with a DataFrame, you lose optimization across that boundary. Collect once, at the end. - Collecting the same query repeatedly. Each
collect()reruns the full plan, including reading the file. Store the result in a variable if you need it more than once.
When to choose lazy
Use lazy for file-based work, multi-step pipelines, and anything where you only need some columns or rows. Eager is fine for small in-memory tables and for quick exploration, where you want to see each result at once.
Exercise
A pipeline starts with pl.scan_csv("sales.csv"), filters on amount, groups by region, and ends with .agg(...). Printing the result shows a query plan instead of rows. What is missing, and why does the plan not run until then?
Show answer
The pipeline is missing .collect(). A LazyFrame only records steps. Polars runs the optimized plan when collect() is called, which returns an eager DataFrame.
Exercise
Why can a lazy query on a wide CSV file read less data than the same steps run eagerly?
Show answer
Polars sees the whole plan first. Projection pushdown reads only the columns the query uses, and predicate pushdown applies the filter at the scan so fewer rows are kept.