A lazy query in Polars

MediumBig data and parallel table processingData analysis

Goal: Building a query plan that Polars optimises before execution.

Python — example.py
import polars as pl

df = pl.DataFrame({
    "city": ["بغداد", "البصرة", "بغداد", "الديوانية", "البصرة", "بغداد"],
    "sales": [120, 80, 150, 60, 95, 130],
})
q = (df.lazy()
       .filter(pl.col("sales") > 70)
       .group_by("city")
       .agg(pl.col("sales").sum().alias("total"), pl.len().alias("n"))
       .sort("total", descending=True))
print(q.collect())

Code explanation

With lazy() nothing runs until collect(), so Polars fuses filtering and aggregation and reads only the needed columns. This is what makes it faster than pandas on large tables.

Requirements

Shell
pip install polars

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

shape: (2, 3)
┌────────┬───────┬─────┐
│ city   ┆ total ┆ n   │
│ ---    ┆ ---   ┆ --- │
│ str    ┆ i64   ┆ u32 │
╞════════╪═══════╪═════╡
│ بغداد  ┆ 400   ┆ 3   │
│ البصرة ┆ 175   ┆ 2   │
└────────┴───────┴─────┘

This example was actually run and tested on 21 November 2026 on a CPU — polars 2.1.0, python 3.13.18

Libraries used

Related examples