Sub topic 14
Reading and scanning CSV files
This chapter assumes you know how to build a DataFrame, read a schema, and write expressions inside select, filter and group_by. It also assumes you have seen collect() on a lazy query. Here you will learn how Polars turns a CSV file into a DataFrame, how type inference can go wrong, and when to scan a file lazily instead of reading it.
Two entry points: read and scan
Polars has two functions for CSV input. They take almost the same arguments.
pl.read_csvparses the file immediately and returns aDataFrame.pl.scan_csvreturns aLazyFrame. It records where the file is and parses nothing until you callcollect().
Because the scan is lazy, the optimizer can push your later filter and column choices down into the file reader. A query that needs 2 of 20 columns then parses only those 2.
A file to work with
The examples use a small file with a missing-value marker (NA), a negative amount, and a date column. The first snippet creates it, so you can run everything as shown.
from pathlib import Path
import polars as pl
Path("sales.csv").write_text(
"order_id,region,amount,sold_on\n"
"1,north,120.5,2024-01-03\n"
"2,south,NA,2024-01-04\n"
"3,north,80,2024-01-05\n"
"4,east,-10,2024-01-05\n"
"5,south,200.25,2024-01-06\n"
)
df = pl.read_csv("sales.csv", null_values="NA", try_parse_dates=True)
print(df.schema)
print(df)The schema shows order_id as Int64, region as String, amount as Float64 and sold_on as Date. Two options did the work:
null_values="NA"tells the parser to treat the textNAasnull. Without it, the wholeamountcolumn would be read asString, becauseNAis not a number.try_parse_dates=Trueconverts columns that look like ISO dates intoDateorDatetime. Without it,sold_onstays aString.
How type inference works
A CSV file stores only text. Polars guesses each column's type by examining the first rows. The infer_schema_length argument sets how many rows it examines, and the default is 100.
This is fast, but it can fail on larger files. If a column holds integers in the first 100 rows and a value like 3.7 on row 5,000, Polars infers Int64 and then fails when it reaches the float. The same problem appears when a column has only empty values in the sampled rows.
You have three ways to handle it:
- Raise the sample size with
infer_schema_length=10_000, or useNoneto scan every row. This is slower, because it reads the full column before parsing. - Name the types you know with
schema_overrides. - Turn inference off with
infer_schema=False, so every column is read asString. You then cast each column explicitly.
typed = pl.read_csv(
"sales.csv",
null_values="NA",
schema_overrides={"order_id": pl.String, "amount": pl.Float64},
try_parse_dates=True,
)
print(typed.schema)schema_overrides changes only the columns you list. Polars still infers the rest.
Identifiers are a good case for overriding. A ZIP code such as 02134 is inferred as an integer, and the leading zero is lost. Reading it as String keeps the value intact. Treat any column you will never do arithmetic on as text.
Choosing columns and rows while reading
You can limit the work at parse time. The next snippet reads two columns and stops after three rows.
small = pl.read_csv(
"sales.csv",
columns=["region", "amount"],
n_rows=3,
null_values="NA",
)
print(small)The options you will use most often are in this table.
| Argument | Purpose |
|---|---|
| `separator` | The delimiter, such as `";"` or `"\t"`. |
| `has_header` | Set to `False` if the first line is data. Columns are then named `column_1`, `column_2`, and so on. |
| `new_columns` | Rename columns as they are read. |
| `skip_rows` | Skip lines before the header, such as a file preamble. |
| `null_values` | Text that should become `null`. It accepts a string, a list, or a per-column dictionary. |
| `schema_overrides` | Set types for named columns. |
| `infer_schema_length` | Rows used to guess types. `None` uses all rows. |
| `ignore_errors` | Turn unparsable values into `null` instead of raising. |
The table lists ignore_errors for completeness, but use it carefully. It hides bad data, and a column that fails to parse can end up full of null values with no warning. It is usually better to read the troublesome column as String and clean it with a cast you control.
Scanning lazily
scan_csv accepts the same arguments as read_csv. The difference is when the work happens.
lazy_result = (
pl.scan_csv("sales.csv", null_values="NA", try_parse_dates=True)
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.sort("region")
)
print(lazy_result.explain())
print(lazy_result.collect())explain() prints the optimized plan without running it. The exact text depends on your Polars version. In the plan you should see the file scan carrying the projection (only the columns region and amount are needed) and the amount > 0 predicate. Both are applied during the scan, so rows and columns that the query never uses are not materialized. The sold_on and order_id columns are never needed here, so they are skipped.
With a 5-row file the saving is invisible. With a 50 GB file it decides whether the query fits in memory.
Schemas on a LazyFrame
A LazyFrame has a schema too, but reading it can force Polars to resolve the plan. In recent versions, call collect_schema():
lf = pl.scan_csv("sales.csv", null_values="NA", try_parse_dates=True)
print(lf.collect_schema())This returns the column names and types without loading the data. Avoid lf.schema and lf.columns in new code, since they can trigger a performance warning.
Errors surface late
When you scan, type inference still happens at scan time, using the first rows. A parse failure deeper in the file raises only when you call collect(). A pipeline that "built fine" can therefore fail much later. Setting schema_overrides for fragile columns avoids this, and so does infer_schema_length=None when the file is small enough.
Many files and large outputs
scan_csv accepts a glob pattern. Files that match are read as one logical table, with their rows stacked in order:
monthly = pl.scan_csv("data/sales_*.csv", null_values="NA")This assumes every file has the same columns. For a result too large to hold in memory, write it straight to disk instead of collecting it. sink_parquet runs the query and writes the output in pieces:
lazy_result.sink_parquet("totals.parquet")A common pattern is to convert a large CSV to Parquet once. Parquet stores types and compresses well, so later reads are faster and need no inference.
Choosing between read and scan
| Situation | Prefer |
|---|---|
| Small file, interactive exploration | `read_csv` |
| You will use the full data repeatedly | `read_csv`, then keep the DataFrame |
| Large file, query uses a few columns or rows | `scan_csv` |
| Several files with the same layout | `scan_csv` with a glob |
| Result larger than memory | `scan_csv` and `sink_parquet` |
If you read the same CSV many times, parse it once and save it as Parquet. Repeated CSV parsing costs time on every run.
Exercise
A file orders.csv has a zip column such as 02134. After pl.read_csv("orders.csv"), the values show as 2134. Why did this happen, and what is the fix?
Show answer
Polars inferred zip as Int64 because every sampled value looked like an integer, and integers have no leading zeros. Read the column as text with pl.read_csv("orders.csv", schema_overrides={"zip": pl.String}).
Exercise
You run pl.scan_csv("big.csv").filter(pl.col("amount") > 0).select("region").collect(). Which two optimizations let this query avoid parsing the whole file, and how can you check that they were applied?
Show answer
Predicate pushdown applies the amount > 0 filter during the scan, and projection pushdown reads only the columns the query needs. Call .explain() on the lazy query before collect() and look for the predicate and the reduced column list in the scan node of the plan.