Sub topic 4
Dtypes and schemas
This chapter assumes you know pandas dtypes such as int64, object and category. It also assumes you can read a Polars select or with_columns call from the earlier chapters.
What a schema is
A Polars schema is an ordered mapping from column name to dtype. Every column has exactly one dtype, and df.schema shows the mapping. Pandas gives you df.dtypes, which is a Series. Polars gives you a schema object you can pass around, compare and reuse when reading data.
How pandas dtypes map to Polars
| pandas | Polars | Note |
|---|---|---|
| `int64` | `Int64` | Polars also has `Int8`, `Int16`, `Int32` and unsigned types. |
| `float64` | `Float64` | Can hold both null and NaN. |
| `object` (strings) | `String` | Stored as UTF-8 text, not Python objects. |
| `bool` | `Boolean` | Can hold null without becoming `object`. |
| `category` | `Categorical` | Use `Enum` when the set of values is fixed. |
| `datetime64[ns]` | `Datetime` | Default time unit is microseconds. |
Two differences matter most when porting code. Integer columns keep their dtype when they contain missing values, so an int column with a gap is not promoted to float64. Also, a column that is not numeric, boolean or date-like becomes String, not a generic Python object.
Inspecting and setting dtypes on read
from io import StringIO
import polars as pl
csv = "id,price,qty,placed\n1,9.5,2,2024-01-05\n2,3.0,,2024-01-06\n"
df = pl.read_csv(StringIO(csv), schema_overrides={"id": pl.Int32})
print(df.schema)
# Schema({'id': Int32, 'price': Float64, 'qty': Int64, 'placed': String})schema_overrides replaces the inferred dtype for the named columns only. The qty column stays Int64 even though one value is missing.
Casting
cast is the equivalent of astype. It is an expression, so it goes inside with_columns.
df = df.with_columns(
pl.col("placed").str.to_date(),
pl.col("qty").cast(pl.Int32),
)
print(df.schema)Dates stored as text need str.to_date, not cast, because the format must be parsed. For plain conversions, cast is strict by default and raises an error if any value cannot be converted. Pass strict=False to get null for those values, which is similar to pd.to_numeric(errors="coerce").
s = pl.Series("raw", ["12", "abc", "7"])
print(s.cast(pl.Int64, strict=False).to_list()) # [12, None, 7]Common errors
- Relying on inference for messy files. Polars infers dtypes from the first rows only (100 by default). A later value of a different type then fails the read. Raise
infer_schema_length, or set the dtype explicitly withschema_overrides. - Expecting silent coercion. A strict cast that fails raises an error. Decide whether you want an error or null, and say so with
strict. - Comparing mismatched dtypes. Joining an
Int32key to anInt64key can raise an error. Cast both sides to the same dtype first. - Keeping
Int64everywhere. Smaller integer dtypes reduce memory. Choose them after checking the value range.
Exercise
A CSV has a column "age" whose first 100 rows are integers, but row 500 contains the text "n/a". pl.read_csv fails on that row. Give two ways to fix this.
Show answer
Read the column as a string with schemaoverrides={"age": pl.String} (or raise inferschema_length), then convert it with pl.col("age").cast(pl.Int64, strict=False). The text "n/a" becomes null and the other values become integers.