Sub topic 6
Knowing the schema without running the query
This chapter assumes you can build a LazyFrame and know that collect() runs it. A schema is the mapping from column names to data types. Polars can often work out the schema of a lazy query from the plan alone, so you get the answer without processing the data.
Why the plan knows the types
Every step in a lazy plan has a known effect on the columns. select keeps some columns. with_columns adds or replaces them. An expression such as pl.col("temp") * 9 / 5 + 32 produces a float, given a float input. Polars follows these rules from the source schema through each node, and the result is the schema of the final output.
Using collect_schema()
Call collect_schema() on a LazyFrame to get the output schema of the whole query:
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
query = (
lf.filter(pl.col("temp") > 4)
.with_columns(temp_f=pl.col("temp") * 9 / 5 + 32)
.group_by("city")
.agg(pl.col("temp_f").mean().alias("avg_f"))
)
schema = query.collect_schema()
for name, dtype in schema.items():
print(name, dtype)The loop prints city String and avg_f Float64. The filter and the aggregation never ran. The returned Schema behaves like an ordered dictionary, with schema.names() for the column names and schema["avg_f"] for one type.
For file scans, the source schema has to come from the file:
- Parquet: Polars reads the metadata, which stores the schema.
- CSV: Polars reads the header and infers types from a sample of rows (100 by default, set with
infer_schema_length). It does not read the whole file.
The cost is small compared with running the query, but it is not zero.
Errors appear before execution
Schema resolution also checks the plan. A reference to a column that does not exist fails at this stage:
import polars as pl
lf = pl.LazyFrame({"x": [1, 2, 3]})
try:
lf.select("y").collect_schema()
except pl.exceptions.ColumnNotFoundError:
print("caught before any data was processed")This makes collect_schema() a cheap way to validate a query that would otherwise run for minutes before failing.
Properties that resolve the schema for you
LazyFrame also has .schema, .columns, .dtypes and .width. Each one resolves the schema in the same way. In recent Polars versions they emit a PerformanceWarning, because resolving a large plan can be slow and the property syntax hides that cost. Use collect_schema() so the cost is explicit. When you need several facts, call it once and reuse the result:
schema = query.collect_schema()
names = schema.names()
dtypes = schema.dtypes()Where it does not work
The optimiser can only predict types it can see through. A Python function passed to map_elements is opaque, so Polars cannot infer its output type. Supplying return_dtype, as in the UDF example later in this tutorial, tells Polars the answer.
Exercise
You have lf = pl.scan_parquet("events.parquet").select("user_id", "ts"). What does lf.collect_schema() read from the file, and why is it preferable to lf.schema in a script?
Show answer
It reads only the Parquet metadata, which holds the schema, and not the column data. collect_schema() is preferable because it makes the schema resolution explicit, and it avoids the PerformanceWarning that the .schema property can emit in recent Polars versions. If the script needs several facts about the schema, call it once and reuse the result.