Sub topic 5
Scanning CSV and Parquet instead of reading them
This chapter assumes you know basic Python and the Polars expression API (pl.col, select, filter, group_by). It also assumes you know what a CSV file and a Parquet file are. You should already know that a LazyFrame records a plan and that collect() runs it.
Read versus scan
pl.read_csv and pl.read_parquet are eager. They load the whole file into a DataFrame before your next line runs. pl.scan_csv and pl.scan_parquet return a LazyFrame instead. The file becomes the source node of a query plan, and its data stays on disk until you call collect().
The optimiser can only help while the data is still unread. That is why scanning matters. With read_csv followed by .filter(...), Polars has already paid for every row and column. With scan_csv followed by .filter(...), the optimiser can hand the filter and the column list to the reader, so the reader loads less.
A first scan
The examples below create their own files, so you can run them as shown.
import polars as pl
pl.DataFrame({
"region": ["EU", "US", "EU", "ASIA", "EU"],
"product": ["a", "a", "b", "b", "a"],
"amount": [10.0, 20.0, 5.5, 7.0, 12.5],
"note": ["x", "y", "z", "w", "v"],
}).write_csv("sales.csv")
lf = (
pl.scan_csv("sales.csv")
.filter(pl.col("region") == "EU")
.group_by("product")
.agg(pl.col("amount").sum().alias("total"))
)
print(lf.explain())
print(lf.collect().sort("product"))In the optimised plan, the CSV scan node carries the extra information. It shows that only three of the four columns are projected, because note is never used. It also shows the region == "EU" condition as a selection attached to the scan. The exact wording of the plan text differs between Polars versions, so look for these two ideas rather than for fixed strings. [Reading explain() output](#) is covered in its own chapter.
Calling scan_csv does very little work. It resolves the file path and works out the schema, and it does not parse the whole file. Parse errors in the data, such as a value that cannot be converted to the inferred type, usually appear at collect() and not at scan_csv.
What each format can push down
Pushdown into a scan is not the same for every file format. The format decides how much the reader can avoid.
| Feature | CSV | Parquet |
|---|---|---|
| Storage layout | Rows of text | Columns, split into row groups |
| Projection pushdown | Unused columns are not kept in memory. The reader still has to scan the bytes of every row. | Unused column chunks are not read at all. |
| Predicate pushdown | Rows that fail the filter are dropped while parsing, so they never reach memory. | Row groups whose min and max statistics rule out a match can be skipped. Remaining rows are filtered. |
| Schema source | Inferred from a sample of rows | Stored in the file footer |
In short, CSV pushdown saves memory and Parquet pushdown also saves I/O. This is one reason to convert large CSV files to Parquet when you query them repeatedly.
Parquet in practice
A Parquet file stores a footer with the schema, the row group layout and per-column statistics. Polars reads the footer first. It then decides which column chunks and which row groups it needs.
import polars as pl
pl.DataFrame({
"id": list(range(1000)),
"value": [i * 0.5 for i in range(1000)],
"label": ["row"] * 1000,
}).write_parquet("numbers.parquet", row_group_size=100)
lf = (
pl.scan_parquet("numbers.parquet")
.filter(pl.col("id") >= 900)
.select("id", "value")
)
print(lf.explain())
print(lf.collect().shape)The file has ten row groups of 100 rows, and id increases through the file. The statistics show that the first nine groups contain no id of 900 or more, so the reader can skip them. The label column is not used, so its chunks are not read. The result has 100 rows and 2 columns.
Row group skipping only works well when the data is clustered on the filtered column. If id values were shuffled, every group would span a wide min and max range, and none could be skipped.
Schema inference for CSV
CSV has no type information, so Polars infers it from a sample. By default it looks at the first 100 rows (infer_schema_length=100). If a column looks like integers in the sample but contains 3.5 on row 5000, the inferred type is wrong, and the error shows up at collect().
You have three ways to prevent this:
- Set
infer_schema_length=Noneto scan the whole file for types. This is slower. - Override only the risky columns with
schema_overrides. - Provide the full
schemayourself, which skips inference.
from pathlib import Path
import polars as pl
Path("amounts.csv").write_text("id,amount\n1,1\n2,2\n3,3.5\n")
lf = pl.scan_csv(
"amounts.csv",
infer_schema_length=2,
schema_overrides={"amount": pl.Float64},
)
print(lf.collect_schema())
print(lf.collect())Without the override, the two-row sample would make amount an integer column, and 3.5 would fail to parse. collect_schema() returns the schema without parsing the data, which is covered later in this tutorial.
Scanning many files
Both scan functions accept glob patterns, so one LazyFrame can cover a directory of files.
import polars as pl
lf = pl.scan_parquet("data/events_*.parquet")The files are treated as one table, and the optimiser applies pushdown to each of them. All files should share the same schema. Parquet also supports Hive-style partitioned directories such as year=2025/month=01/. The partition values can then be used to skip whole files, but that behaviour depends on your Polars version and options, so check the documentation for hive_partitioning.
Other formats follow the same pattern. scan_ndjson and scan_ipc exist for newline-delimited JSON and Arrow IPC files.
Common mistakes
- Using
read_*and then.lazy(). The file is already fully loaded, so pushdown into the reader cannot happen. Usescan_*from the start. - Scanning the same file in several places without thinking about cost. Each
scan_csvreads the file separately when collected. Usecollect_allfor queries that share a source, or cache a filtered result in a Parquet file. - Assuming the file is read once at
scan_*time. The file is read atcollect(), so changes made between the two calls affect the result. - Trusting a small inference sample. Rare values later in a CSV file can break type inference. Set the schema for production pipelines.
- Using
scan_csvon data you will query many times. CSV must be parsed every time. Converting once to Parquet usually pays off.
Exercise
You run pl.read_parquet("big.parquet").filter(pl.col("country") == "NO").select("user_id") and it uses far more memory than expected. Rewrite the query so that Polars can skip unused columns and, where possible, unused row groups. Then say how you would confirm the change worked.
Show answer
Use pl.scan_parquet("big.parquet").filter(pl.col("country") == "NO").select("user_id").collect(). The scan keeps the data on disk, so the optimiser can push the projection (country and user_id only) and the predicate into the Parquet reader. Print lf.explain() before calling collect() and check that the scan node lists only the needed columns and shows the country == "NO" filter. Row groups can be skipped only if the file's statistics for country allow it, which works best when the data is sorted or clustered by country.