Sub topic 1
Eager versus lazy: two ways to run the same query
Prerequisites
This chapter assumes you know basic Python and have used Polars DataFrames. You should be comfortable with pl.col, select, filter, with_columns and group_by. You don't need to know how the optimiser works. That comes in later chapters.
Two execution modes
Polars can run a query in two ways.
- Eager execution runs each step as soon as you call it. Every method on a
DataFramereturns a newDataFramewith the result. - Lazy execution records each step in a plan. Nothing runs until you ask for the result. Every method on a
LazyFramereturns a newLazyFramethat holds a longer plan.
The expressions are the same in both modes. Only the moment of execution changes.
The same query, both ways
The example below filters rows and selects one column, first eagerly and then lazily.
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))This prints True. Both versions give the same result.
In the eager version, filter runs on all rows and produces an intermediate DataFrame. Then select runs on that. In the lazy version, df.lazy() converts the DataFrame into a LazyFrame. The filter and select calls only add steps to the plan. The work happens when collect() runs.
Why the lazy version matters
Because a LazyFrame sees the whole query before running it, Polars can rewrite the plan to do less work. Here are two examples:
- It can read only the columns the query uses.
- It can apply a filter while reading a file, so it never loads the rows you discard.
The eager version can't do this. Each call only knows about its own step. It can't know that a later step will discard most of the data.
When to use each
| Situation | Better choice |
|---|---|
| Exploring data interactively and wanting to see each step | Eager |
| Small data that fits easily in memory | Either |
| Reading large CSV or Parquet files | Lazy |
| A multi-step pipeline you will run repeatedly | Lazy |
Exercise
Exercise
You run lf = df.lazy().filter(pl.col("temp") > 4).select("city") and see no output and no error, even if temp contains a million rows. Why, and what do you call to get the result?
Show answer
lazy() returns a LazyFrame, and filter and select only add steps to its plan. No computation happens yet. Call lf.collect() to run the plan and get a DataFrame.
Exercise
Why can a lazy query sometimes do less work than the same eager query?
Show answer
A LazyFrame holds the whole plan before it runs, so Polars can rewrite it. For example, it can skip columns the query never uses, or filter rows while reading. Eager steps run one at a time and can't see what comes later.