typestar

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

  1. LazyFrame records operations without running them.
  2. explain shows the optimized query plan.
  3. collect executes it and returns the result.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Lazy & SQL, step 25 of 32 in Polars.

← Previous Next →