Sub topic 2
From eager DataFrames to lazy queries
This chapter assumes you can write basic Polars: pl.col, filter, with_columns, group_by, and agg. It also assumes you know what CSV and Parquet files are. The previous chapter showed why loading a huge file into memory fails. Here you learn the first tool for avoiding that: describing the work before running it.
Eager evaluation: every step runs immediately
Polars has two kinds of frame objects. A DataFrame is eager. Each method call runs at once and returns a new DataFrame that holds real data in memory.
import polars as pl
df = pl.DataFrame(
{
"user_id": [1, 1, 2, 3, 3, 3],
"status": ["ok", "error", "ok", "ok", "ok", "error"],
"amount": [10.0, 5.0, 7.5, 3.0, 4.0, 1.0],
}
)
eager = (
df.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.sort("user_id")
)
print(eager)Each call in this chain produces an intermediate result:
filterbuilds a newDataFramewith the matching rows.group_by(...).agg(...)builds another.sortbuilds a third.
Eager code has two properties that matter for large data.
- The input must already be in memory.
pl.read_csv("events.csv")parses the whole file, every row and every column, before your first filter runs. - Polars sees one step at a time. It cannot know that you only need two of the twenty columns, or that you filter out 95% of the rows later. It has already done the work by then.
For a file that fits comfortably in RAM, this is fine and often convenient. For a file that does not fit, the read fails before your logic starts.
Lazy evaluation: describe first, run later
A LazyFrame is lazy. Calling filter, select, with_columns, group_by, or join on it does not touch any data. It adds a step to a recorded description of the computation, called the query. Nothing runs until you ask for a result, usually with collect().
You can turn an existing DataFrame into a LazyFrame with .lazy(). Here is the same pipeline written lazily.
import polars as pl
df = pl.DataFrame(
{
"user_id": [1, 1, 2, 3, 3, 3],
"status": ["ok", "error", "ok", "ok", "ok", "error"],
"amount": [10.0, 5.0, 7.5, 3.0, 4.0, 1.0],
}
)
lf = (
df.lazy()
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.sort("user_id")
)
print(type(lf)) # a LazyFrame, not a DataFrame
print(lf.collect_schema()) # column names and types, no data processed
result = lf.collect() # the query runs here
print(result)Compare what each object gives you:
| Row | `DataFrame` (eager) | `LazyFrame` (lazy) |
|---|---|---|
| Holds data | Yes, in memory | No, holds a query description |
| Method calls | Run immediately | Record a step |
| Optimization across steps | None | The optimizer rewrites the whole query |
| Result | The frame itself | Produced by `collect()` or a sink |
| Can show rows directly | Yes | Only after running part of the query |
Because a LazyFrame holds no rows, print(lf) shows the plan, not data. To peek at a few rows, run a small version of the query: lf.head(5).collect().
Why delaying the work helps
Once Polars has the entire query, it can optimize it before running anything. The optimizer works on the full description, so it can do things an eager call sequence cannot:
- Skip unused columns. If the final result only needs
user_idandamount, other columns never need to be read from the source. - Filter early. A filter written at the end of a chain can be applied at the start, so later steps handle fewer rows.
- Combine and simplify expressions. Redundant computations can be merged or removed.
These rewrites are called pushdown and related optimizations. The chapters "Reading the query plan" and "Predicate and projection pushdown" cover them in detail. For now, the point is that laziness is what makes them possible. It is also the foundation for the streaming engine, which needs a complete query so it can decide how to process the data in chunks.
Converting an eager pipeline
Converting a pipeline takes three changes:
- Replace the
read_*function with itsscan_*counterpart. For CSV,read_csvbecomesscan_csv. - Keep the middle of the pipeline the same. The expression API is nearly identical on both frame types.
- End the chain with
collect().
This example writes a small file first so it runs as shown.
import polars as pl
pl.DataFrame(
{
"user_id": [1, 2, 3, 3],
"status": ["ok", "error", "ok", "ok"],
"amount": [10.0, 5.0, 7.5, 3.0],
"note": ["a", "b", "c", "d"],
}
).write_csv("events.csv")
# Eager version: reads all four columns, then filters.
eager = (
pl.read_csv("events.csv")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
# Lazy version: describes the same work, then runs it once.
lazy = (
pl.scan_csv("events.csv")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
.collect()
)
print(eager.equals(lazy)) # TrueThe two results are identical. The difference is in how they get there. The eager version reads every column, including note, into memory. The lazy version gives the optimizer the chance to read only the columns the query uses. The next chapter covers scan_csv and scan_parquet properly.
Common mistakes
These errors come up often when people move to lazy code.
Loading eagerly, then going lazy. This pattern gives up the main benefit:
import polars as pl
pl.DataFrame({"a": [1, 2, 3]}).write_csv("events.csv")
# The whole file is already in memory before .lazy() is called.
lf = pl.read_csv("events.csv").lazy().lazy() is useful for optimizing steps on data that is already loaded. It cannot undo an eager read. For files, start from a scan_* function.
Forgetting to collect. A LazyFrame that is never collected does no work. If a script builds a query and prints nothing or writes nothing, check that the chain ends with collect() or a sink.
Collecting too early. If you call collect() in the middle of a pipeline and then continue with the resulting DataFrame, everything before that point ran without knowledge of what comes after. You lose optimization across the boundary, and the intermediate result must fit in memory. Collect once, at the end.
Running the same query twice. Each collect() on a LazyFrame runs the whole query again. The frame does not remember a previous result. If you need the output more than once, store the collected DataFrame in a variable.
Expecting errors at the call site. In lazy code, a wrong column name in select or filter is usually reported when the query is resolved, at collect() or when you ask for the schema, and not on the line where you wrote the mistake. If a traceback points at collect(), read the message for the real cause. Calling collect_schema() while developing catches many mistakes without processing any data.
Checking what the optimizer will do
explain() prints the optimized plan as text without running the query. Use it as a quick check that your lazy pipeline looks the way you intend.
import polars as pl
pl.DataFrame(
{
"user_id": [1, 2, 3],
"status": ["ok", "error", "ok"],
"amount": [10.0, 5.0, 7.5],
}
).write_csv("events.csv")
lf = (
pl.scan_csv("events.csv")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print(lf.explain())The exact text depends on your Polars version, so this chapter does not reproduce it. The next chapters teach you how to read it.
When eager is still the right choice
Lazy is not always better. Eager frames are simpler when you are exploring a small dataset interactively and want to see rows after every step. Many Polars workflows start eager for exploration and move to lazy once the logic is settled and the data grows. Because the expression API is shared, the move is mostly a matter of changing the entry point and adding collect().
Summary
- A
DataFrameruns each step immediately and holds its data in memory. ALazyFramerecords steps and holds a query. - Nothing in a lazy query runs until
collect()or a sink runs it. - Seeing the whole query lets the optimizer skip unused columns and apply filters early.
- To convert a pipeline, swap
read_*forscan_*, keep the expressions, and collect once at the end. - Lazy evaluation is the base the streaming engine builds on, but a plain
collect()still builds the full result in memory.
Exercise
A teammate writes pl.read_parquet("events.parquet").lazy().filter(pl.col("status") == "ok").collect() and says the pipeline is lazy, so it will not run out of memory on a file larger than RAM. What is wrong with this reasoning, and how would you change the first step?
Show answer
read_parquet is eager. It loads the whole file into memory before .lazy() is called, so the memory problem happens before any lazy step exists. Replace it with pl.scan_parquet("events.parquet") so the source is only described, not loaded. Also note that a plain collect() still builds the full result in memory, so the result must be small enough, or you must use the streaming engine or a sink.
Exercise
You build lf = pl.scan_csv("events.csv").filter(pl.col("amount") > 0) and call lf.collect() twice, once to print the result and once to write it with write_csv. How many times does the query run, and what would you change?
Show answer
It runs twice, because each collect() re-executes the whole query. Collect once into a variable, for example result = lf.collect(), then print result and call result.write_csv(...). If the result is too large to hold in memory, write it directly with a sink instead.