Sub topic 3
Scanning files instead of reading them
This chapter assumes you know basic Python, can write Polars expressions (pl.col, filter, with_columns, group_by), and know the difference between CSV and Parquet. It covers how scan_csv and scan_parquet differ from read_csv and read_parquet, what a scan actually does, and the errors people hit when they first switch.
Reading versus scanning
pl.read_csv and pl.read_parquet are eager. They open the file, decode every row and column, and return a DataFrame that holds all of it in memory. Each later step runs on that full copy.
pl.scan_csv and pl.scan_parquet are lazy. They return a LazyFrame. A LazyFrame is not data. It is a description of a query whose first step is "read this file". Calling a scan reads at most the file's metadata, and the data stays on disk.
import polars as pl
# Eager: the whole file is decoded into memory here.
df = pl.read_csv("events.csv")
# Lazy: nothing is read yet beyond what is needed to describe the query.
lf = pl.scan_csv("events.csv")
print(type(df)) # <class 'polars.dataframe.frame.DataFrame'>
print(type(lf)) # <class 'polars.lazyframe.frame.LazyFrame'>Work only happens when you ask for a result. That is the job of collect(), collect(engine="streaming"), or a sink such as sink_parquet. Later chapters cover those. Here the point is that a scan defers reading until Polars knows what the whole query needs.
What a scan does
When you call a scan function, Polars does a small amount of work up front.
- It resolves the path or glob pattern into a list of files.
- It reads enough of the file to determine the schema, meaning the column names and data types.
- It records the scan as the first node of the query plan.
For Parquet, the schema comes from the file footer, which is cheap and exact. For CSV, there is no stored schema, so Polars infers types by sampling the first rows. This difference causes the most common scan problems, covered below.
import polars as pl
lf = pl.scan_parquet("events/*.parquet")
# The schema is known without reading the data.
print(lf.collect_schema())Use collect_schema() to get the schema of a LazyFrame. It resolves the schema without loading the data. Avoid lf.schema in new code, because on a lazy query it can be expensive for some plans and is discouraged in recent Polars versions.
Converting an eager pipeline
The conversion is mostly mechanical. Replace the read with a scan, keep your expressions, and add a step that produces the result.
import polars as pl
# Before: eager
df = pl.read_csv("events.csv")
result = df.filter(pl.col("status") == "ok").select("user_id", "amount")
# After: lazy
result = (
pl.scan_csv("events.csv")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
.collect()
)The expressions are identical. What changes is when they run. In the eager version, Polars reads all columns first and then filters. In the lazy version, Polars sees the whole chain before reading anything. It can then skip the columns you never use and apply the filter while reading. The next chapters explain this optimization. Here it is enough to know that scanning is what makes it possible.
Scanning many files
A glob pattern lets one scan cover many files. This is common for Parquet data that arrives in daily or hourly pieces.
import polars as pl
lf = pl.scan_parquet("events/*.parquet")Polars treats the matched files as one table. They need compatible schemas. If one file has a column the others lack, or a column has a different type, you will see a schema error at collect time or at scan time, depending on the format and Polars version.
Files are matched in a defined order, but do not depend on that order for correctness unless you sort explicitly.
CSV and Parquet scans compared
| Aspect | `scan_csv` | `scan_parquet` |
|---|---|---|
| Schema source | Inferred from a sample of rows | Stored in the file footer |
| Column skipping | Must still scan the text to find fields | Reads only the needed column chunks |
| Row skipping | Filter applies after rows are parsed | Can skip row groups using min/max statistics |
| Type safety | Types can be guessed wrongly | Types are exact |
| Typical cost | Higher CPU for parsing | Lower I/O and CPU |
A CSV scan still helps with memory, because the streaming engine can process the file in chunks. But it cannot skip data as effectively as Parquet. If you scan the same CSV repeatedly, converting it once to Parquet usually pays off. A later chapter covers sinking CSV to Parquet.
Controlling schema inference for CSV
By default scan_csv infers types from the first 100 rows. If a column looks like integers in those rows but contains a string later, the query fails when it reaches that row. A typical message is a parse error that says a value could not be parsed as the inferred type.
You have two ways to fix this.
import polars as pl
# Option 1: look at more rows before deciding types.
lf = pl.scan_csv("events.csv", infer_schema_length=10_000)
# Option 2: state the types you know.
lf = pl.scan_csv(
"events.csv",
schema_overrides={"user_id": pl.Int64, "amount": pl.Float64},
)
print(lf.collect_schema())infer_schema_length=None scans the whole file to infer types. That is safe but reads the entire file once before your query starts, which is slow on a large file. Explicit schema_overrides is usually the better choice for a file you will scan more than once, because it is fast and does not guess.
Common errors
- File not found at collect time. A scan may not open every file immediately. A wrong path can show up when you collect. Check the path, and remember relative paths resolve from the working directory of the process, not from your script.
- Empty glob. A pattern that matches nothing raises an error. Print the pattern's matches with
glob.globif you are unsure. - Modifying the file between scan and collect. The scan holds a plan, not a snapshot. If another process rewrites the file before you collect, you read the new contents or get an error.
- Expecting a scan to be fast to collect. A scan is fast to create. The query still has to read the data when it runs.
- Calling
.collect()right after the scan.pl.scan_csv("big.csv").collect()is the same asread_csv. It loads everything. Put filters and column selection before the collect, or use a sink.
Inspecting what you built
A LazyFrame is safe to print, but it shows the plan rather than the data. To confirm what the query will do, use explain().
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print(lf.explain())The next chapter shows how to read this output. For now, notice that the scan appears as the leaf of the plan, and that the filter and columns you chose appear alongside it.
Exercise
A colleague writes pl.scan_csv("big.csv").collect().filter(pl.col("amount") > 0) and finds it runs out of memory, just like pl.read_csv. Why does this happen, and how would you change the code so the filter is part of the lazy query?
Show answer
Calling .collect() immediately after the scan executes the query with no filter in it, so the whole file is loaded into a DataFrame. The filter then runs on the in-memory copy, which is the same as an eager read. Move the filter before the collect: pl.scan_csv("big.csv").filter(pl.col("amount") > 0).collect(). Polars can then apply the filter while reading. For data larger than memory, use collect(engine="streaming") or a sink instead of a plain collect.
Exercise
You scan a CSV file with default settings. The query fails partway through with an error that a value could not be parsed as an integer. What caused it, and what are two ways to fix it?
Show answer
The default schema inference looks only at the first 100 rows. The column looked like integers there, but a later row holds a non-integer value, so parsing fails when the query reaches it. Fix it by raising infer_schema_length (or setting it to None to scan the entire file), or by declaring the type with schema_overrides, for example schema_overrides={"user_id": pl.String} if the column is really text.