Sub topic 3
Reading, writing and inspecting data
This chapter assumes you know pandas I/O (read_csv, to_parquet, head, info) and have installed Polars with pip install polars. You will map each of those calls to its Polars equivalent.
Reading files
Polars readers return a DataFrame with a default row number and no index. The function names are close to pandas, but several arguments are renamed.
| pandas | Polars |
|---|---|
| `read_csv(sep=";")` | `read_csv(separator=";")` |
| `usecols=[...]` | `columns=[...]` |
| `nrows=100` | `n_rows=100` |
| `na_values=[...]` | `null_values=[...]` |
| `parse_dates=[...]` | `try_parse_dates=True` |
| `dtype={...}` | `schema_overrides={...}` |
| `index_col=...` | none (the index does not exist) |
Polars reads CSV files with multiple threads. It infers types from the first rows, which is controlled by infer_schema_length. If a column's type changes after those rows, the read fails instead of silently falling back to object. Raise infer_schema_length or set schema_overrides for that column.
Writing files
The example below writes a small file, reads it back, and saves it as Parquet.
import polars as pl
pl.DataFrame(
{
"order_id": [1, 2, 3],
"region": ["EU", "US", "EU"],
"price": [9.5, 20.0, None],
"qty": [3, 5, 2],
"date": ["2026-01-05", "2026-01-06", "2026-01-07"],
}
).write_csv("orders.csv")
df = pl.read_csv(
"orders.csv",
try_parse_dates=True,
null_values=["NA"],
schema_overrides={"order_id": pl.Int32},
)
df.write_parquet("orders.parquet")
same = pl.read_parquet("orders.parquet")
print(same.equals(df))The output is True. Writers take no index=False argument, because there is no index to leave out. Parquet keeps the dtypes, so prefer it over CSV for intermediate files.
Inspecting a frame
print(df.shape) # (3, 5)
print(df.schema) # column names mapped to dtypes
print(df.head(2))
df.glimpse() # one line per column, like a transposed head
print(df.describe()) # summary statistics
print(df.null_count())| pandas | Polars |
|---|---|
| `df.dtypes` | `df.schema`, `df.dtypes` |
| `df.info()` | `df.glimpse()`, `df.schema` |
| `df.isna().sum()` | `df.null_count()` |
| `df.memory_usage()` | `df.estimated_size()` |
Common errors
- Passing
index_colorindex=Falseraises aTypeError. Delete these arguments. - A date column that stays
strmeans parsing failed. Check withdf.schema, then convert it explicitly in the string and datetime chapter. - Reading a very large file with
read_csvloads it all into memory. The lazy API chapter showsscan_csvas the alternative.
Exercise
A pandas call reads pd.read_csv("data.csv", sep=";", usecols=["id", "amount"], na_values=["NA"], nrows=500). Write the Polars equivalent.
Show answer
pl.readcsv("data.csv", separator=";", columns=["id", "amount"], nullvalues=["NA"], n_rows=500)