Sub topic 4
Nothing runs until collect()
This chapter assumes you know basic Python and the Polars expression API (pl.col, select, filter, with_columns, group_by). It also assumes you have seen the difference between eager and lazy execution. Here you will see what a LazyFrame does with each method call and when work actually happens.
Building a plan is not running it
Every method on a LazyFrame returns another LazyFrame. None of them touch the data. Each call adds one step to a logical plan, which is a tree describing the query. The plan runs only when you ask for a result.
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
query = (
lf.filter(pl.col("temp") > 4)
.group_by("city")
.agg(pl.col("temp").mean().alias("avg_temp"))
)
print(type(query))This prints <class 'polars.lazyframe.frame.LazyFrame'>. The filter and the aggregation have not been computed. query is only a description of them.
Running the query with collect()
collect() takes the plan, optimises it, executes it, and returns an ordinary DataFrame.
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
query = (
lf.filter(pl.col("temp") > 4)
.group_by("city")
.agg(pl.col("temp").mean().alias("avg_temp"))
)
result = query.collect()
print(type(result))
print(result.sort("city"))Rows from group_by come back in no guaranteed order, so the example sorts them. Each call to collect() runs the whole plan again. Polars does not cache the result inside the LazyFrame. If you need the result twice, keep the DataFrame that collect() returned.
Common errors
- Printing a LazyFrame and expecting rows.
print(query)shows a description of the query, not data. Callcollect()first. - Using DataFrame-only methods on a LazyFrame. Methods that need materialised data, such as indexing with
lf[0], are not available lazily. Collect first. - Calling
collect()too early. If you collect in the middle of a pipeline and then call.lazy()again, the optimiser cannot move work across that boundary. Collect once, at the end. - Expecting errors at build time. Many mistakes, such as a wrong column name, are caught only when the plan is resolved or run. A typo in
pl.col("tmep")may not fail untilcollect().
Exercise
A colleague writes df2 = lf.filter(pl.col("x") > 0) on a LazyFrame over a 20 GB Parquet file and says the filter "finished instantly". What actually happened, and when will the 20 GB be processed?
Show answer
Nothing was processed. filter only added a step to the logical plan and returned a new LazyFrame. Work happens when collect() (or a sink such as sink_parquet) is called on df2 or on a query built from it. At that point Polars optimises the plan, which may let it read much less than 20 GB.