Optimize a complete query
Assemble filters, projections, joins, and aggregations before execution.
Polars · Class
polars.LazyFrame represents a deferred computation graph over tabular data. It enables whole-query optimization and parallel execution, and is Polars' preferred high-performance mode.
A LazyFrame represents a deferred computation graph rather than immediately executing operations. You can construct transformations such as filtering and projection, allowing Polars to optimize the complete query before materialization with collect or another sink.
class polars.LazyFrame(data=None, schema=None, *, strict=True, schema_overrides=None, orient=None, infer_schema_length=100, nan_to_null=False)| Name | Type | Description |
|---|---|---|
data | dict, Sequence, ndarray, Series, or pandas.DataFrame | Two-dimensional input data; dictionary values must contain Sequences, Generators, or a range. |
schema | SchemaDefinition | None | Column names for the resulting LazyFrame. |
orient | Orientation | None | Whether to infer the schema from the input data. |
strict | bool | Whether to raise an error when schema inference encounters incompatible data. |
A polars.LazyFrame representing the deferred computation graph.
import polars as pl
lf = pl.LazyFrame({"name": ["Ada", "Linus"], "score": [9, 7]})
result = (
lf.filter(pl.col("score") >= 8)
.select("name")
.collect()
)
print(result)Build a lazy query, then execute it with collect to obtain a DataFrame.
Assemble filters, projections, joins, and aggregations before execution.
Process tabular data with Polars' deferred execution model.
Convert an existing eager DataFrame workflow to deferred execution.
LazyFrame is Polars' deferred query representation. Transformations build a computation graph, and execution is deferred until a terminal operation such as collect materializes the result.
Follow-up: Why can laziness improve performance? The complete query can be optimized as a whole before execution, rather than running each transformation independently.
The constructor accepts several two-dimensional input forms, including dictionaries, sequences, ndarrays, Series, and pandas DataFrames. A dictionary must provide sequences, generators, or a range as its values.
Follow-up: How can an eager DataFrame become lazy? Call its lazy() method; this is equivalent to constructing a LazyFrame from the same data.
A LazyFrame is designed for whole-query optimization and parallel execution. It is the preferred and highest-performance mode for Polars workloads that can be expressed lazily.
Follow-up: When should execution happen? Delay materialization until the complete query is assembled, then use collect or an appropriate sink.
polars.DataFramepolars.DataFrame.lazypolars.LazyFrame.collectpolars.LazyFrame.explain