Sub topic 3
Reading, writing and inspecting data
This chapter covers moving data in and out of Polars and checking what you loaded. It assumes you know pandas read_csv, to_csv, head, info and describe, and that you have installed Polars with pip install polars. Parquet support is built in. Converting to pandas needs pyarrow.
Reading files
Polars has a read_* function for each common format. The names match pandas, but the options differ in a few places.
| pandas | Polars | Notes |
|---|---|---|
| `pd.read_csv` | `pl.read_csv` | Eager read into a DataFrame |
| `pd.read_parquet` | `pl.read_parquet` | Preserves the stored schema |
| `pd.read_json` | `pl.read_json`, `pl.read_ndjson` | Newline-delimited JSON has its own reader |
| `pd.read_excel` | `pl.read_excel` | Needs an extra engine such as `fastexcel` |
A DataFrame returned by read_csv has no index. The first column is a normal column, so there is no index_col argument and no reset_index step.
import polars as pl
df = pl.read_csv("orders.csv")
print(df.head())Common read options
Several pandas arguments have a renamed Polars equivalent.
| pandas argument | Polars argument |
|---|---|
| `usecols` | `columns` |
| `dtype` | `schema_overrides` |
| `na_values` | `null_values` |
| `parse_dates=True` | `try_parse_dates=True` |
| `nrows` | `n_rows` |
| `skiprows` | `skip_rows` |
| `sep` | `separator` |
df = pl.read_csv(
"orders.csv",
columns=["order_id", "region", "price", "qty", "ordered_at"],
schema_overrides={"order_id": pl.Utf8, "qty": pl.Int32},
null_values=["", "NA", "n/a"],
try_parse_dates=True,
)Reading a CSV is also where type inference happens. Polars looks at the first 100 rows by default (infer_schema_length=100). If a column looks like integers for 100 rows and then contains a decimal, the read fails with a parse error. You have two fixes:
- Raise
infer_schema_length, or passNoneto scan the whole file. - Declare the column type in
schema_overrides.
df = pl.read_csv("orders.csv", infer_schema_length=10_000)Writing files
Writing is a method on the DataFrame. Unlike pandas, there is no index=False argument to remember, because there is no index to write.
df.write_csv("out.csv")
df.write_parquet("out.parquet")
df.write_ndjson("out.ndjson")Parquet is the better choice for intermediate files in a migration. It stores dtypes, so a round trip does not re-run inference, and it is compressed and columnar. CSV loses type information such as dates and categorical columns.
Inspecting a DataFrame
The first checks after loading are shape, schema, and a sample of rows.
print(df.shape) # (rows, columns)
print(df.columns) # list of names
print(df.schema) # mapping of name to dtype
print(df.head(5))
print(df.tail(5))
print(df.sample(5))df.schema replaces df.dtypes as the most useful view. In current Polars, df.dtypes returns a list without names. df.schema pairs each name with its dtype.
The following table maps the inspection calls you already use.
| pandas | Polars |
|---|---|
| `df.info()` | `df.schema`, `df.estimated_size()` |
| `df.describe()` | `df.describe()` |
| `df.isna().sum()` | `df.null_count()` |
| `df["c"].value_counts()` | `df["c"].value_counts()` |
| `df["c"].nunique()` | `df["c"].n_unique()` |
| `len(df)` | `df.height` or `len(df)` |
Two differences matter when porting code.
describe()in Polars returns a DataFrame with astatisticcolumn rather than an index of statistic names. You select from it with expressions, not.loc.null_count()counts only nulls. It does not count floating-point NaN values. The null versus NaN chapter covers this in detail.
stats = df.describe()
print(stats.filter(pl.col("statistic") == "mean"))Printing wide frames
Polars truncates output to fit the terminal. The display options live in pl.Config, which replaces pd.set_option.
pl.Config.set_tbl_rows(20)
pl.Config.set_tbl_cols(12)
pl.Config.set_fmt_str_lengths(60)You can also use with pl.Config(tbl_rows=50): to change settings only inside a block. This avoids leaking display changes into other code.
Reading many files
A glob pattern reads several files into one DataFrame, which replaces the pd.concat([pd.read_csv(f) for f in files]) loop. The files need compatible schemas.
df = pl.read_parquet("data/orders_*.parquet")For large inputs, prefer scan_csv and scan_parquet. They return a LazyFrame and read nothing until you call collect(). A later chapter covers this in depth.
Moving data from Python objects
You often build small frames by hand in tests. The constructor takes a dictionary of columns.
df = pl.DataFrame(
{
"region": ["north", "south", "north"],
"price": [10.0, 25.5, 40.0],
"qty": [3, 1, 4],
}
)
print(df.schema)Polars infers Utf8 (shown as String), Float64 and Int64 for these lists. If you need a specific type, pass schema={"qty": pl.Int32, ...}.
Common errors
- A parse error on a late row. Type inference saw only the first rows. Raise
infer_schema_lengthor setschema_overrides. - Code that uses
df.index. DataFrames have no index. Move the key into a column and use filters or joins. - Code that calls
df.loc[...]. Usefilterfor rows andselectfor columns. - Dates read as strings. Pass
try_parse_dates=True, or convert later withstr.to_date. - A column with leading zeros loses them. Declare it as
pl.Utf8before reading.
Exercise
A CSV has a zip column with values like 02134, and a price column that is whole numbers for the first 500 rows and then contains 12.5. Write a pl.read_csv call that keeps the zip codes intact and reads the price column without failing.
Show answer
pl.readcsv("file.csv", schemaoverrides={"zip": pl.Utf8, "price": pl.Float64}). Declaring zip as Utf8 keeps the leading zero. Declaring price as Float64 avoids the parse error caused by inference seeing only integers in the first 100 rows. Raising inferschemalength would also fix the price column.
Exercise
In pandas you call df.isna().sum() to count missing values per column. What is the Polars equivalent, and what kind of missing value does it miss?
Show answer
df.null_count(). It counts null values only. It does not count floating-point NaN values, which Polars treats as a separate value.