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 an eager DataFrame. It also assumes you have run pl.read_csv. Everything below uses the same expressions you already know. What changes is when they run.
Eager versus lazy
An eager DataFrame runs each operation as soon as you call it. A LazyFrame does not. Each method call adds a step to a query plan, which is a tree of operations. No data is processed until you call .collect(), which optimizes the plan, runs it, and returns a DataFrame.
Because Polars sees the whole query before running it, it can reorder and trim the work. An eager chain cannot be improved this way, because each step has already run when the next one is written.
| Row | `DataFrame` (eager) | `LazyFrame` (lazy) |
|---|---|---|
| Runs when | Each method is called | `.collect()` or a `sink_*` call |
| Holds | Data in memory | A query plan, plus a data source |
| Optimizer | None across steps | Whole-query optimization |
| Inspect data | `print`, indexing, `.row()` | Not available until collected |
| Typical source | `pl.read_csv`, dictionaries | `pl.scan_csv`, `df.lazy()` |
The expression syntax is identical in both. Most DataFrame methods you use for transformations also exist on LazyFrame.
Creating a LazyFrame
There are two common ways to get one:
- Call
.lazy()on an existingDataFrame. - Call a
scan_*function such aspl.scan_csvorpl.scan_parquet. These do not read the file up front. They record where the data lives.
The second route gives the biggest gains, because the optimizer can tell the file reader which rows and columns it needs. The following setup creates a small file so you can run every example in this chapter.
import polars as pl
pl.DataFrame(
{
"region": ["north", "south", "north", "east", "south", "east"],
"channel": ["web", "web", "store", "store", "web", "store"],
"amount": [120, -15, 80, 200, 60, 0],
}
).write_csv("sales.csv")Building and running a query
The next query filters out non-positive amounts and totals the rest by region. Nothing is computed until collect().
lf = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(type(lf))
print(lf.sort("region").collect())type(lf) prints polars.lazyframe.frame.LazyFrame. The result of collect() is a normal DataFrame with the totals: east 200, north 200, south 60.
Two details matter here:
lfis only a plan. Callinglf.sort("region")returns a newLazyFrame, andlfitself is unchanged.- Each
collect()runs the whole plan again, including re-reading the file. If you need the result more than once, store the collectedDataFramein a variable.
What the optimizer does
You can read the plan before running anything. explain() returns the optimized plan as text.
print(lf.explain())
print(lf.explain(optimized=False))The exact text differs between Polars versions, so look at the structure and not the wording. Plans read from the bottom up: the scan is at the bottom and the final operation is at the top. Comparing the two outputs shows what changed. The main rewrites are:
- Predicate pushdown. A filter moves as close to the data source as possible. For
scan_csv, rows withamount <= 0can be dropped while the file is being read, so they never reach later steps. - Projection pushdown. Only the columns the query uses are read. This query needs
regionandamount, sochannelis skipped. The scan line in the plan typically shows something likePROJECT 2/3 COLUMNS. - Slice pushdown. A
head(n)orlimit(n)can stop the scan early. - Common subplan elimination. If the same sub-query appears twice in one plan, it is computed once.
- Expression simplification. Constants are folded and redundant operations removed.
Pushdown only helps if the source supports it. CSV and Parquet scanners do. A Python function used as a data source, or an eager DataFrame converted with .lazy(), has less to optimize at the source, because the data is already in memory.
Checking the schema without running the query
A LazyFrame has no data to print, but it can tell you its output column names and types. Use collect_schema(), which resolves the plan's schema without executing it.
print(lf.collect_schema())
print(lf.collect_schema().names())This is a cheap way to confirm that a long chain produces the columns and dtypes you expect. Avoid the older lf.schema property and lf.columns. In recent versions they resolve the schema each time and emit a performance warning.
Errors appear at collect time
Because nothing runs until collect(), mistakes in a lazy chain often surface late. A misspelled column name, for example, raises an error when the plan is resolved or collected, not on the line where you wrote the typo.
bad = pl.scan_csv("sales.csv").select(pl.col("amout")) # typo
try:
bad.collect()
except pl.exceptions.ColumnNotFoundError as err:
print("caught:", type(err).__name__)When a long chain fails, read the error message first. Then bisect: call collect() or collect_schema() on shorter prefixes of the chain until you find the step that breaks.
Running several queries and writing results
If you have several lazy queries over the same source, pl.collect_all runs them together. Polars can share work between them, such as a common scan.
by_region = (
pl.scan_csv("sales.csv")
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.sort("region")
)
by_channel = (
pl.scan_csv("sales.csv")
.group_by("channel")
.agg(pl.len().alias("n"))
.sort("channel")
)
region_df, channel_df = pl.collect_all([by_region, by_channel])
print(region_df)
print(channel_df)Sometimes the result is too big to hold in memory, or you only want it on disk. The sink_* methods run the query and write the output without first building a full DataFrame for the caller.
(
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.sink_parquet("positive_sales.parquet")
)
print(pl.read_parquet("positive_sales.parquet"))Which operations a streaming or sink run supports has grown over releases. Operations that need to see all rows may force a fallback to the in-memory engine. In recent versions you can request the streaming engine explicitly with collect(engine="streaming"). Older versions used collect(streaming=True). Check the documentation for your installed version.
Common mistakes
- Forgetting
collect(). Printing aLazyFrameshows its plan, not rows. If you see a plan where you expected a table, you have not collected yet. - Collecting too early. Calling
collect()in the middle of a pipeline and then continuing eagerly throws away optimization. Collect once, at the end. - Collecting the same plan repeatedly. Each call re-reads and recomputes. Collect once and reuse the
DataFrame. - Using row-level eager features. Indexing,
.row()and iterating rows are not available on aLazyFrame. Collect first, or better, express the logic as an expression. - Expecting
.lazy()to speed up a bad query. The optimizer reorders native expressions. It cannot see inside a Python function passed tomap_elements, so those steps limit what it can optimize. - Trusting small-data timings. On a six-row file, lazy and eager look the same. The difference shows up with large files, wide tables and selective filters.
Exercises
Exercise
You scan a CSV with 40 columns, filter rows where amount > 0, then select only region and amount. Which two optimizations let Polars avoid reading most of the file, and where in lf.explain() would you look to confirm them?
Show answer
Predicate pushdown moves the filter into the scan so non-matching rows are dropped while reading. Projection pushdown reads only the needed columns, region and amount. In the plan, look at the scan node at the bottom. It should show the pushed-down filter condition and a column count such as PROJECT 2/40 COLUMNS. Comparing with lf.explain(optimized=False) shows that the unoptimized plan keeps the filter above the scan and reads all columns.
Exercise
A teammate writes df = pl.scan_csv("sales.csv").filter(pl.col("amount") > 0) and then calls print(df["region"]). What goes wrong, and what are two ways to fix it?
Show answer
A LazyFrame does not support column indexing, because it holds a plan and no data. Fix 1: call .collect() first, as in df.collect()["region"]. Fix 2: stay lazy and ask for the column in the query, as in df.select("region").collect(). The second keeps projection pushdown working, so it is usually better.