Sub topic 3
Scanning files instead of reading them
This chapter assumes you know basic Python, Polars expressions (pl.col, filter, with_columns, group_by), and the difference between CSV and Parquet. It covers scan_csv and scan_parquet, which are the entry point for every larger-than-memory query in the rest of the tutorial.
Read versus scan
pl.read_csv is eager. It parses the whole file into a DataFrame before your next line runs. If the file is larger than available RAM, the process fails with an out-of-memory error.
pl.scan_csv and pl.scan_parquet are lazy. They do not load data. They return a LazyFrame, which is a description of a query. Polars looks only at enough of the file to learn the column names and types. No rows are loaded until you ask for a result.
import polars as pl
# Eager: parses the whole file now.
df = pl.read_csv("events.csv")
# Lazy: records "read this file" as the first step of a plan.
lf = pl.scan_csv("events.csv")
print(type(df)) # <class 'polars.dataframe.frame.DataFrame'>
print(type(lf)) # <class 'polars.lazyframe.frame.LazyFrame'>Because a LazyFrame is only a plan, Polars can read less data than the file contains. Chapter 5 covers how it does that. For now, the point is that the scan gives the optimizer something to work with.
Scanning many files
scan_parquet accepts a glob pattern. Polars treats all matching files as one table, so you do not need to concatenate them yourself.
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
result = lf.collect(engine="streaming")
print(result.head())Nothing runs until collect. The engine="streaming" argument asks Polars to process the data in chunks, which a later chapter explains.
The files in a glob should share a schema. If columns or types differ between files, the scan can fail or give unexpected types.
What a scan knows about your data
A LazyFrame has a schema, so you can inspect it without reading any rows.
import polars as pl
lf = pl.scan_parquet("events/*.parquet")
print(lf.collect_schema())Use collect_schema() rather than the older .schema attribute on a LazyFrame. The older attribute can trigger extra work and gives a warning in recent Polars versions.
For CSV, the schema comes from type inference on a sample of rows. A column that looks like integers in the sample may contain text later in the file, which causes a parse error mid-query. You can avoid this in two ways:
- Pass
schema_overrides={"user_id": pl.Utf8}to fix specific columns. - Pass
infer_schema_length=Noneto scan every row when inferring. This is slow on large files.
Parquet stores its schema in the file footer, so it has no inference problem. This is one reason Parquet suits large data better than CSV.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Out-of-memory error with a lazy query | Calling `collect()` without `engine="streaming"`, or collecting a very large result | Use the streaming engine, or write the result with a sink |
| `ComputeError` while parsing a CSV partway through | Type inferred from too few rows | Set `schema_overrides` or `infer_schema_length` |
| Schema mismatch across files in a glob | Files were written with different columns or types | Make the schema consistent when writing the files |
| Code runs instantly but gives no output | The `LazyFrame` was never collected | Call `collect`, or use a sink |
Putting the scan in the plan
Think of a scan as the leaf of your query. Every filter, select, and group_by you chain after it is added on top of that leaf. Polars can then reorder and simplify the steps before running anything.
Exercise
You have a 40 GB CSV file and 16 GB of RAM. Why does pl.read_csv("big.csv") fail while pl.scan_csv("big.csv") on the same line does not, and what must you still do before you get a result?
Show answer
read_csv is eager and tries to load all 40 GB into memory, which exceeds 16 GB. scan_csv only builds a LazyFrame, a plan that reads just the schema and no rows. You must still run the query, for example with collect(engine="streaming") or a sink such as sink_parquet, and the result must fit in memory unless you use a sink.
Exercise
A scan_csv query fails halfway through with a parse error on a column named user_id. The first rows of the file hold integers, but later rows hold values like "u-1042". Name two ways to fix it.
Show answer
Set schema_overrides={"user_id": pl.Utf8} so the column is read as text. Alternatively, set infer_schema_length=None so Polars checks every row when inferring types, which is slower. Converting the file to Parquet, which stores its schema, also avoids the problem.