Sub topic 2
Knowing the Schema Without Running the Query
Assume basic Python, Polars DataFrames, and expressions such as pl.col, filter, and select. This chapter focuses on how Polars plans and optimises lazy queries.
Knowing the schema without running the query
A LazyFrame stores instructions instead of rows. collect_schema() resolves the planned column names and data types without executing the complete query:
import polars as pl
lf = (
pl.LazyFrame({
"region": ["EU", "US"],
"amount": [10, 20],
})
.filter(pl.col("amount") > 0)
.select("region")
)
print(lf.collect_schema())Schema resolution may inspect source metadata or read file headers, but it does not produce the final DataFrame. Use it to check column names and types before calling collect().
A query is a plan
Each lazy operation adds a node to a logical plan. A logical plan is a tree describing what the query should do. A scan or in-memory DataFrame is usually near the bottom. Filters, projections, and aggregations appear above it.
The plan describes the result, not necessarily the order in which Polars will perform every operation.
Reading explain() output
explain(optimized=False) shows the plan close to how you wrote it. explain() shows the optimised plan:
import polars as pl
lf = (
pl.scan_csv("sales.csv")
.filter(pl.col("region") == "EU")
.select("product", "amount")
)
print(lf.explain(optimized=False))
print(lf.explain())Look for scan nodes, filters, projections, and aggregations. In the optimised output, a filter or selected columns may appear inside the scan node.
What the optimiser rewrites
The optimiser changes the plan while preserving the query result. It can simplify expressions, remove unused columns, move filters earlier, and reuse repeated expressions. These rewrites reduce I/O, memory use, or computation.
Predicate pushdown: filter early, read less
Predicate pushdown moves a filter as close as possible to its source. For a Parquet or CSV scan, Polars can sometimes reject rows while reading rather than after loading every row.
For example, this query asks for EU rows only:
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("region") == "EU")
.select("product", "amount")
)
result = lf.collect()The result is the same as filtering after reading the file, but predicate pushdown can reduce the data read and processed. Python user-defined functions can block this optimisation because the optimiser cannot inspect their behavior.
Exercise
Which method runs a LazyFrame and returns its result as a DataFrame?
Show answer
collect().