Sub topic 3
Creating a LazyFrame with lazy() and LazyFrame()
This chapter assumes you know Python and the Polars expression API (pl.col, select, filter, with_columns, group_by). It also assumes you know the difference between eager and lazy execution from the earlier chapters. Here you will learn the two ways to build a LazyFrame from data already in memory, what each one does, and which mistakes people commonly make with them.
What a LazyFrame holds
A LazyFrame does not hold a table of results. It holds a logical plan, which is a description of the steps that will produce a table. Each method you call (filter, select, group_by and so on) returns a new LazyFrame whose plan has one more step. Nothing is computed until you call collect(), which a later chapter covers.
Two entry points create a LazyFrame from in-memory data:
DataFrame.lazy()converts an existingDataFrame.pl.LazyFrame(...)builds one directly from Python data.
Files are a third entry point, scan_csv and scan_parquet, and have their own chapter.
Converting with lazy()
Use lazy() when you already have a DataFrame, for example one returned by a library or built by earlier eager code.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
lf = df.lazy()
print(type(lf))
query = lf.filter(pl.col("temp") > 4).select("city")
print(type(query))
print(query.collect())Both type calls print LazyFrame. Only the last line computes anything.
lazy() is cheap. It wraps the existing columns in a plan node that reads from the DataFrame, and it does not copy the column data. You can convert back and forth without a large cost, though each collect() runs the plan it holds.
Calling lazy() on a LazyFrame is harmless and returns an equivalent LazyFrame. This helps when you write a function that accepts either type.
Building directly with pl.LazyFrame()
pl.LazyFrame(...) takes the same kinds of input as pl.DataFrame(...). These include a dict of columns, a list of dicts, a list of rows, and a numpy array. It also accepts the same schema, schema_overrides, orient and strict arguments. Use it when the data starts as Python objects, so you do not create a DataFrame only to convert it.
import polars as pl
# Dict of columns, with dtypes inferred.
a = pl.LazyFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]})
# Rows as tuples. The schema names the columns and orient says how to read the data.
b = pl.LazyFrame(
[("Oslo", 3.0), ("Lima", 19.5)],
schema=["city", "temp"],
orient="row",
)
# Explicit dtypes.
c = pl.LazyFrame(
{"city": ["Oslo", "Lima"], "temp": [3.0, 19.5]},
schema={"city": pl.String, "temp": pl.Float32},
)
print(a.collect_schema())
print(b.collect_schema())
print(c.collect_schema())Polars builds the data in memory when you construct the LazyFrame. Only the query steps you add afterwards are lazy. The constructor itself is not deferred, so a bad input fails at that line, not at collect().
Looking at a LazyFrame
Printing a LazyFrame does not show rows. It shows the plan as written so far, because no rows exist yet.
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3, 4]})
query = lf.with_columns(y=pl.col("x") * 2).filter(pl.col("y") > 4)
print(query) # the plan text, not a table
print(query.explain()) # the optimised plan, covered in a later chapter
print(query.collect()) # the actual rowsThe explain() method is the tool you will use most for inspecting what a LazyFrame will do.
Pitfalls
The same mistakes come up repeatedly with LazyFrame objects.
Forgetting to collect
Every method returns a LazyFrame, so a script that never calls collect() finishes without error and without doing the work. If a result looks like a plan instead of a table, you probably forgot collect().
Eager habits that do not apply
A LazyFrame has no row count and no values to index into, so these eager idioms fail:
lf["x"]andlf[0]are not supported. Uself.select("x")orlf.head(1), which stay lazy, then collect.len(lf)does not work. Compute the count in the query withlf.select(pl.len()).collect().lf.head(5)returns anotherLazyFrame, not five rows.
Asking for the schema the wrong way
Reading lf.columns, lf.dtypes, lf.schema or lf.width forces Polars to resolve the plan. On a large or complicated query this can be slow, and recent versions emit a PerformanceWarning for it. Call lf.collect_schema() instead, which says plainly that it resolves the schema without running the data. A later chapter covers it.
Converting too early
A pipeline that runs eager steps and then calls .lazy() only optimises what comes after that call. The eager steps before it already ran in full. Convert at the start of the pipeline, so the optimiser sees the whole query.
import polars as pl
raw = pl.DataFrame({"a": range(1_000), "b": range(1_000), "c": range(1_000)})
# Weak: the wide eager select runs before the optimiser can see the filter.
weak = raw.select("a", "b", "c").lazy().filter(pl.col("a") < 10).select("a").collect()
# Better: the optimiser sees every step.
better = raw.lazy().select("a", "b", "c").filter(pl.col("a") < 10).select("a").collect()
print(weak.equals(better))Both give the same table. The difference is how much work happens before the optimiser takes over.
Converting back and forth in a loop
Each collect() followed by lazy() ends one plan and starts another. This throws away any optimisation across the boundary. Keep the query as one LazyFrame and collect once at the end, or use collect_all when you need several results.
How much does lazy() help on in-memory data?
Less than it does for files. The largest wins from lazy execution come from reading less data from disk, and in-memory data has no read step to skip. The optimiser can still do useful work on a DataFrame source, such as dropping unused columns and applying filters early. It can also avoid computing the same expression twice and simplify expressions. For a single filter on a small table, eager code is just as good, and the difference is not measurable.
Summary table
| Goal | Call | Result type |
|---|---|---|
| Make an existing DataFrame lazy | `df.lazy()` | `LazyFrame` |
| Build from Python data | `pl.LazyFrame(data, schema=...)` | `LazyFrame` |
| Read a file lazily | `pl.scan_csv(path)`, `pl.scan_parquet(path)` | `LazyFrame` |
| Run the plan | `lf.collect()` | `DataFrame` |
| Show the plan | `lf.explain()` | `str` |
Exercise
A colleague writes n = len(pl.LazyFrame({"x": [1, 2, 3]})) and gets an error. How do you get the row count correctly, and what type does the call return before you collect it?
Show answer
Compute the count inside the query and collect it: pl.LazyFrame({"x": [1, 2, 3]}).select(pl.len()).collect(). This gives a one-row DataFrame with the count (use .item() to get the number). Before collect(), select(pl.len()) returns a LazyFrame, because a LazyFrame has no known length until the plan runs.
Exercise
You write raw.select("a", "b", "c").lazy().filter(pl.col("a") < 10).select("a"). Why does moving .lazy() to directly after raw help the optimiser?
Show answer
The eager select already ran in full before lazy() was called, so the optimiser never saw it. With raw.lazy() first, the plan includes every step, and the optimiser can drop unused columns and apply the filter early across the whole query.