An eager query does each step the moment you write it. A lazy query only writes the steps down, then looks at the whole list, throws away the work it does not need, and runs what is left once. On big files that difference is the one between waiting and not waiting.
The idea in plain words
Where we are. Topics 1 to 7 used the eager API. Here the same operations are written against a LazyFrame. We scan a file without reading it, build a query, read the plan the optimizer made, and collect. The two payoffs are reading fewer columns and filtering rows while reading, and both show up in the plan text.
A way of running a query in which each step only adds to a plan, and nothing is computed until you ask for the result. Because the whole plan is known first, the engine can reorder steps and skip data that the result never needs.
A recipe, not data
pl.scan_csv(path) returns a LazyFrame at once, without touching the file. You can still ask what the columns will be with collect_schema(), and you chain filter, select, group_by exactly as before. Each call returns another LazyFrame. Only collect() reads the file and returns a real DataFrame.
# Scan KO: a LazyFrame whose columns are known, with nothing read yetlazy = scan_bars(folder, "KO")print(type(lazy).__name__, lazy.collect_schema().names())print("after a filter it is still", type(lazy.filter(pl.col("volume") > 0)).__name__)print("collect gives", type(lazy.collect()).__name__, "with", lazy.collect().height, "rows")
LazyFrame ['symbol', 'date', 'open', 'high', 'low', 'close', 'volume'] after a filter it is still LazyFrame collect gives DataFrame with 6699 rows
Read the plan
explain() prints the plan Polars will run. Compare what we wrote with what it runs: we scanned the whole file, filtered, then selected one column, but the plan shows PROJECT 2/6 COLUMNS, so only two of the six columns are read, and the date test sits as a SELECTION inside the scan, so rows are dropped while reading. The optimizer did both on its own. explain(optimized=False) shows the plan as written.
# The query we wrote, and the lines of the optimized plan that show what Polars skipsquery = pl.scan_csv("data/KO.csv", try_parse_dates=True).filter(pl.col("date") >= date(2020, 1, 1)).select(pl.col("close").mean())for line in query.explain().splitlines(): if "PROJECT" in line or "SELECTION" in line or "SCAN" in line: print(line.strip())print("mean close since 2020:", round(mean_close_since(folder, "KO", date(2020, 1, 1)), 3))
Csv SCAN [data/KO.csv]
PROJECT 2/6 COLUMNS
SELECTION: col("date") >= 2020-01-01
mean close since 2020: 60.542One query over many files
Scans can be stacked with pl.concat, still lazily, so five files become one query: filter, group, sort, and a single collect() at the end. If you must run several different queries, hand them all to pl.collect_all([...]): Polars runs them in parallel and computes shared parts, such as a common scan, once.
# One lazy query over all five files, collected once at the endsymbols = ["AAPL", "JPM", "XOM", "JNJ", "KO"]summary = summary_lazy(folder, symbols, date(2025, 1, 1))print(summary.select("symbol", "bars", pl.col("mean_close").round(2), "max_volume").rows())
[('AAPL', 410, 251.74, 261775450), ('JNJ', 410, 197.08, 25620954), ('JPM', 410, 294.31, 27170689), ('KO', 410, 73.08, 53357493), ('XOM', 410, 125.89, 53942143)]# Two different queries, collected togetherlatest, earliest = collect_many([scan_bars(folder, "KO").tail(1), scan_bars(folder, "KO").head(1)])print("first close", earliest["close"][0], "| last close", latest["close"][0])
first close 19.4546 | last close 91.1
The moment you call collect() or read_csv, the data is in memory and the optimizer has nothing left to optimize. Build the whole query first, collect once, and collect only what you need: filter and select before the collect, never after. Use eager frames for small results you want to look at.
What the tasks ask
- 1`scan_bars` and `mean_close_since`
pl.scan_csv(..., try_parse_dates=True),selectwithpl.lit(symbol), no collect; thenfilter,select(mean),collect().item(). - 2`summary_lazy` and `collect_many`A list of scans with
with_columns(pl.lit(s)),pl.concat,filter,group_by("symbol").agg(...),sort, onecollect();pl.collect_all(frames).
pl.read_csv("big.csv"), then .filter(...) and .select("close"). Why is pl.scan_csv("big.csv") with the same two calls and a collect() usually faster?Lab · what's graded
4 tasks · 100 pts- A recipe, not data:
scan_bars25 pts - Filter before reading:
mean_close_since25 pts - One query, many files:
summary_lazy25 pts - Collect together:
collect_many25 pts