Sub topic 1
Eager and Lazy Queries in Polars
Prerequisites
This chapter assumes basic Python, Polars DataFrames, and expressions such as pl.col, select, and filter. You should also know the difference between CSV and Parquet files.
Eager versus lazy execution
Eager execution runs each operation immediately. A DataFrame is created, transformed, and returned after every step. This is useful for small data and interactive exploration because you can inspect each result.
Lazy execution records operations in a query plan. Polars waits until you request the result, then optimises the complete plan before running it. Use it for file-backed data, long pipelines, or queries where reducing input work matters.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
eager = df.filter(pl.col("temp") > 4).select("city")
lazy = df.lazy().filter(pl.col("temp") > 4).select("city")
result = lazy.collect()
print(eager.equals(result))Expressions are inspectable building blocks
An expression describes a computation, such as pl.col("temp") > 4. It does not immediately calculate values. Polars can combine expressions into a plan and inspect their columns, filters, and dependencies. Prefer native expressions when possible because they give the optimiser more information than an arbitrary Python function.
Creating a LazyFrame
Call df.lazy() to create a LazyFrame from an existing in-memory DataFrame. You can also construct one directly:
lf = pl.LazyFrame({"x": [1, 2, 3]})
query = lf.filter(pl.col("x") > 1).select("x")A LazyFrame represents a query, not materialised results.
Nothing runs until `collect()`
Most lazy operations only extend the plan. collect() executes the plan and returns a DataFrame. This boundary is useful: build the complete query first, then let Polars optimise it.
Scanning files lazily
Use scan_csv() or scan_parquet() instead of reading a file into memory first:
lf = (
pl.scan_parquet("events.parquet")
.filter(pl.col("country") == "NO")
.select("user_id", "ts")
)
df = lf.collect()The scan becomes part of the plan. Polars can then push filters and column selection toward the file reader.
Exercise
Which call changes a LazyFrame query plan into an executed DataFrame?
Show answer
collect().