Sub topic 4
Nothing runs until collect()
This chapter assumes you know basic Python and can use the Polars expression API (pl.col, select, filter, with_columns, group_by). You should also know what eager and lazy execution mean at a high level. Here you will look at what a LazyFrame does when you call methods on it, and what collect() does.
A LazyFrame stores a recipe
A LazyFrame does not hold the results of your steps. It holds a description of the steps, called a logical plan. Each method you call, such as filter, select or with_columns, returns a new LazyFrame whose plan has one more node. No data is processed at that point.
import polars as pl
calls = []
def double(v):
calls.append(v)
return v * 2
lf = pl.LazyFrame({"x": [1, 2, 3]}).with_columns(
y=pl.col("x").map_elements(double, return_dtype=pl.Int64)
)
print(type(lf).__name__) # LazyFrame
print(len(calls) > 0) # False: the function has not run
df = lf.collect()
print(type(df).__name__) # DataFrame
print(len(calls) > 0) # True: collect() ran the plan
print(df)The Python function double records every call in the calls list. Building lf leaves the list empty. The calls happen only inside collect(). This is a useful trick for checking when work really happens.
What collect() does
When you call collect(), Polars takes the plan built so far and does three things in order:
- It optimises the plan. It may reorder steps, drop unused columns and push filters toward the data source. Later chapters cover each rewrite.
- It executes the optimised plan.
- It returns a
DataFrameholding the result.
collect() is the normal way to turn a lazy query into a result. The input LazyFrame is not changed. Plans are immutable, so you can keep extending one LazyFrame in different directions.
import polars as pl
base = pl.LazyFrame({"city": ["Oslo", "Lima", "Oslo"], "temp": [3.0, 19.5, 5.0]})
cold = base.filter(pl.col("temp") < 10)
warm = base.filter(pl.col("temp") >= 10)
print(cold.collect())
print(warm.collect())
print(base.collect()) # base still has all three rowsWhat returns a LazyFrame and what does not
You can tell whether a call has done work by looking at what it returns.
| Call | Returns | Does it run the query? |
|---|---|---|
| `filter`, `select`, `with_columns`, `sort`, `join`, `head` | `LazyFrame` | No |
| `group_by(...).agg(...)` | `LazyFrame` | No |
| `collect()` | `DataFrame` | Yes |
| `collect_schema()` | `Schema` | No, answered from the plan |
| `explain()` | `str` | No, only describes the plan |
| `sink_parquet(path)` | `None` | Yes, and writes a file |
The collect_schema(), collect_all() and sink_parquet() calls are covered in later chapters. They are included here so you can see that collect() is one of several ways to trigger execution.
Consequences you will notice
Work and errors appear late
Because nothing runs while you build the query, a mistake in an early step can show up only at collect(). A typical case is a filter that refers to a column that does not exist. Where exactly the error appears depends on the Polars version, since newer releases check more of the plan early. Do not assume that building a query without an error means the query is valid.
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3]})
try:
bad = lf.filter(pl.col("price") > 1) # no column named price
bad.collect()
except pl.exceptions.ColumnNotFoundError as err:
print("caught:", type(err).__name__)Wrapping both the build step and the collect() in the try block means this example behaves the same whichever step raises the error. In real code, test queries on small data early so that you see errors close to where you wrote them.
Each collect() runs the whole query again
A LazyFrame does not cache its result. If you call collect() twice on the same LazyFrame, Polars runs the full plan twice. That means two file reads, two sorts and two group-bys.
import polars as pl
lf = pl.LazyFrame({"g": ["a", "b", "a"], "v": [1, 2, 3]}).group_by("g").agg(
pl.col("v").sum()
)
result = lf.collect() # runs the plan once
print(result.height)
print(result.sort("g")) # reuse the DataFrame, not the LazyFrameCollect once, keep the DataFrame, and reuse it. If you need several results from one shared plan, collect_all can share work between them, as a later chapter explains.
Peeking at a lazy query
To look at a few rows while developing, add a head step before collect():
import polars as pl
lf = pl.LazyFrame({"n": list(range(1_000_000))}).filter(pl.col("n") % 2 == 0)
print(lf.head(3).collect())The head(3) becomes part of the plan, so the optimiser knows only three rows are needed. This is better than collecting everything and then slicing the DataFrame. The behaviour is covered under slice pushdown in a later chapter.
DataFrame habits that do not carry over
Many DataFrame features need real data, so a LazyFrame does not offer them. You cannot index it like lf["x"], and it has no row count until you collect. If you call a method that does not exist on a LazyFrame, add a collect() first, or find the lazy equivalent. For example, use collect_schema() instead of looking at columns directly.
Common mistakes
- Forgetting
collect(). Printing aLazyFrameshows the plan, not data, which looks like a bug until you notice the type. - Collecting too early, then continuing with
DataFramemethods. The optimiser never sees the later steps. - Calling
collect()several times on oneLazyFrameinstead of storing the result. - Putting side effects, such as printing or appending to a list, inside a UDF and expecting them at build time. They happen at
collect(), and possibly more than once or in a different order than you expect.
Exercise
A colleague writes lf = pl.scan_csv("data.csv").filter(pl.col("a") > 0), then calls lf.collect() in three different cells of a notebook to look at the data. What happens each time, and what should they change?
Show answer
Each collect() runs the whole plan again: it reads data.csv, applies the filter and builds a new DataFrame. That is three file reads, and the results can differ if the file changes in between. They should call collect() once, store the DataFrame (for example df = lf.collect()), and use df in the other cells. If they only want a quick look, lf.head(5).collect() reads far less.