Sub topic 1
Eager versus lazy: two ways to run the same query
Polars can run a query in two modes. In eager mode, each step runs the moment you call it. In lazy mode, each step is recorded, and Polars runs the whole recorded query later. This chapter explains how the two modes differ and which one to use. Later chapters cover the lazy machinery in detail.
Prerequisites
This chapter assumes you have:
- Basic Python.
- Some familiarity with Polars DataFrames and the expression API:
pl.col,select,filter,with_columnsandgroup_by. - A basic idea of what reading a CSV or Parquet file means.
You need Polars installed (pip install polars). Every example below runs as written.
Eager execution: one step at a time
A DataFrame is eager. Every method you call does its work immediately and returns a new DataFrame holding real data.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
step1 = df.filter(pl.col("temp") > 4)
step2 = step1.select("city")
print(type(step1).__name__)
print(step2)step1 is a full table in memory before select starts. That has two benefits. You can print or inspect any intermediate result, and a Python traceback points at the exact line that failed.
The cost is that each call is planned alone. When filter runs, Polars does not know that you will keep only city afterwards. It filters every column of every matching row, and select then throws most of that away. On four rows this is invisible. On a 20 GB file it matters.
Lazy execution: describe first, run later
A LazyFrame is lazy. Calling filter or select on it does no work on the data. It adds a node to a plan, which is a description of the query so far. Nothing is computed until you ask for the result with collect().
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
# Eager: each step runs immediately and returns a DataFrame.
eager = df.filter(pl.col("temp") > 4).select("city")
# Lazy: the same steps only build a plan; collect() runs it.
lazy = df.lazy().filter(pl.col("temp") > 4).select("city")
result = lazy.collect()
print(eager.equals(result))The program prints True. Both versions return the same rows. The difference is in the middle: lazy is still a LazyFrame after the select, and no filtering has happened. Only collect() triggers execution.
Why recording the query helps
Because Polars sees the whole query before running it, it can rewrite the plan. The result stays the same, but the work gets cheaper. Two examples show the idea:
- If the query only needs three columns, Polars can avoid reading the others from the file.
- If a filter removes most rows, Polars can apply it as early as possible, so later steps handle less data.
These rewrites have names (projection pushdown, predicate pushdown) and are covered in their own chapters. For now, remember the principle: an eager call sees one step, and a lazy query sees all of them.
Lazy mode also helps beyond optimisation. A plan can report its output schema without touching data. It can be run by the streaming engine on data larger than memory. And one plan can be reused or inspected before you commit to running it.
Comparing the two modes
| Aspect | Eager (`DataFrame`) | Lazy (`LazyFrame`) |
|---|---|---|
| When work happens | At each method call | At `collect()` or a sink |
| What a method returns | A `DataFrame` with data | A `LazyFrame` holding a plan |
| Optimisation across steps | None, each call is separate | Yes, the optimiser sees the whole plan |
| Inspect intermediate values | Easy, print any step | Not directly, you must collect |
| Where mistakes usually appear | At the line that caused them | Often when the query runs |
| Reading files | `read_csv`, `read_parquet` load all data | `scan_csv`, `scan_parquet` read only what is needed |
Moving between the modes
You can switch at any point.
import polars as pl
df = pl.DataFrame({"x": [1, 2, 3, 4]})
lf = df.lazy() # DataFrame -> LazyFrame, no data copied for the plan
back = lf.collect() # LazyFrame -> DataFrame, runs the plan
print(type(lf).__name__)
print(type(back).__name__)Many eager DataFrame operations are themselves implemented by building a small lazy query and collecting it immediately. This means eager code is not a different engine. It is the lazy engine used one step at a time, without the chance to optimise across steps.
When each mode is appropriate
Use lazy when:
- You read from files. Scanning lets Polars skip columns and, for formats that support it, skip rows.
- The query has several steps, such as filter, then group, then aggregate.
- The data is large, or may be larger than memory.
- You are writing a reusable pipeline or a script that runs unattended.
Use eager when:
- You are exploring in a notebook and want to see each result as you go.
- The data is small and the query is one or two steps.
- You need a concrete value in the middle of a computation, for example to branch on a count in Python.
A common workflow is to explore eagerly on a small sample, then rewrite the finished query lazily for the full data. Because the expression API is the same in both modes, this is usually a change of the entry point (read_csv to scan_csv) and a final collect().
Common mistakes
- Forgetting
collect(). Printing aLazyFrameshows the plan, not rows, and nothing has run. If your script seems to finish instantly and produces no output data, check for a missingcollect(). - Collecting too early. Calling
collect()in the middle of a pipeline and then going back with.lazy()ends the plan at that point. The optimiser cannot push a later filter into work that has already run. - Expecting early errors. In lazy mode a misspelled column name typically surfaces when the query is resolved or run, not on the line where you wrote it. Keep that in mind when debugging a long chain.
- Assuming lazy is always faster. For a tiny in-memory table the planning overhead can outweigh the gain. The benefit grows with data size and query complexity.
Exercise
You run lf = pl.scan_csv("sales.csv").filter(pl.col("region") == "EU").select("amount"), and the line returns almost instantly even though the file is 10 GB. Has Polars filtered the data? What must you do to get rows, and why can this be cheaper than pl.read_csv("sales.csv").filter(...).select("amount")?
Show answer
No. scan_csv and filter only record steps in a plan, so lf is a LazyFrame and no data has been filtered. You must call lf.collect() to run the plan and get a DataFrame. It can be cheaper because the optimiser sees the whole query and needs only the region and amount columns, so it can avoid reading and holding the others. read_csv loads the entire file into memory first, and only then runs the filter and select.
Exercise
A colleague writes lf.collect().lazy().filter(pl.col("x") > 0).collect() inside a pipeline. What is the drawback compared with removing the first collect().lazy()?
Show answer
The first collect() runs the plan to completion and materialises a full DataFrame. The later filter is then a new, separate plan, so the optimiser cannot push it into the earlier work. Removing collect().lazy() keeps one plan, and the filter can be applied early.