Lazy frames in Python
Deferring work so Polars can optimize the whole query.
import polars as pl
lazy = pl.LazyFrame({
"city": ["akl", "wlg", "akl", "chc", "wlg"],
"temp": [18, 14, 21, 12, 16],
})
query = (
lazy
.filter(pl.col("temp") > 13)
.group_by("city")
.agg(pl.col("temp").mean().alias("avg_temp"))
.sort("avg_temp", descending=True)
)
plan = query.explain()
result = query.collect()
How it works
LazyFramerecords operations without running them.explainshows the optimized query plan.collectexecutes it and returns the result.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 17
- Characters to type
- 315
- Tokens
- 129
- Three-star pace
- 115 tpm
At the three-star pace of 115 tokens a minute, this run takes about 67 seconds.
Step 1 of 4 in Lazy & SQL, step 25 of 32 in Polars.