Sub topic 2
From eager DataFrames to lazy queries
This chapter assumes you know basic Python and Polars expressions (pl.col, filter, with_columns, group_by). It also assumes you have used a DataFrame to filter and aggregate rows. The previous chapter showed that loading a large file all at once can exhaust memory. Here you change how a pipeline is written so Polars can avoid that.
Eager execution
Eager execution means each operation runs as soon as you call it. pl.read_csv reads the whole file into a DataFrame. Each later filter or select runs immediately on data that is already in memory.
import polars as pl
df = pl.DataFrame(
{
"user_id": [1, 1, 2, 3],
"status": ["ok", "error", "ok", "ok"],
"amount": [10.0, 5.0, 7.5, 3.0],
}
)
# Each step runs immediately.
result = df.filter(pl.col("status") == "ok").select("user_id", "amount")
print(result)With a file, the first step is the problem: pl.read_csv("events.csv") must finish reading every row and column before the filter can discard anything.
Lazy execution
Lazy execution means Polars records your operations instead of running them. The object that holds the recorded steps is a LazyFrame. Nothing is computed until you ask for a result.
import polars as pl
df = pl.DataFrame(
{
"user_id": [1, 1, 2, 3],
"status": ["ok", "error", "ok", "ok"],
"amount": [10.0, 5.0, 7.5, 3.0],
}
)
lf = (
df.lazy()
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print(type(lf)) # a LazyFrame, no work done yet
result = lf.collect() # runs the whole query
print(result)Calling .lazy() converts a DataFrame to a LazyFrame. .collect() runs the recorded query and returns a DataFrame.
The expression syntax is the same in both modes. Converting a pipeline mostly means changing where it starts and adding a final call that runs it.
Why lazy helps with memory
Because a lazy query is a description, Polars can see the whole job before it starts. That allows it to:
- Skip columns that the query never uses.
- Apply filters while reading, so rejected rows are never kept.
- Reorder or combine steps when the result is unchanged.
Later chapters cover these optimizations and the streaming engine, which runs the optimized plan in chunks. This chapter covers only the change in style that makes them possible.
Common errors when converting
- Treating a LazyFrame like a DataFrame. Calling
lf.head()returns another LazyFrame, not rows. Nothing prints until you callcollect(). - Forgetting
collect(). A pipeline that seems to do nothing usually never ran. - Collecting too early. If you call
collect()in the middle of a pipeline and continue with a DataFrame, you lose the optimizer's view of the later steps. Chain all steps first, then collect once. - Expecting errors immediately. Some mistakes, such as a misspelled column name, appear only when the query runs, not when you write the step.
Converting a file-based pipeline
For data in a file, the change is one line. The eager version is pl.read_csv("events.csv"). The lazy version replaces it with pl.scan_csv("events.csv"), and the rest of the chain stays the same, ending with .collect(). The next chapter explains the scan functions.
Exercise
A colleague writes lf = pl.scan_csv("big.csv").filter(pl.col("amount") > 0) and then prints lf. They see a description of a query instead of rows. What did they forget, and why does this design help the optimizer?
Show answer
They forgot to call collect() (or another method that runs the query). A LazyFrame only records operations, so Polars can see the whole query before running it and can skip unused columns and filter rows while reading.