Sub topic 4
Dtypes and schemas
This chapter assumes you know the basic pandas dtypes (int64, float64, object, category, datetime64) and can run short Polars snippets. It covers what each pandas dtype becomes in Polars, how to read and enforce a schema, and where casting behaves differently. Missing values are covered in the next chapter.
What a schema is
A Polars schema is an ordered mapping from column name to dtype. Every DataFrame has one, and you read it from df.schema.
import polars as pl
df = pl.DataFrame({
"id": [1, 2, None],
"price": [9.5, None, 3.0],
"name": ["a", "b", None],
})
print(df.schema) # id: Int64, price: Float64, name: String
print(df.dtypes) # [Int64, Float64, String]Note that id is still Int64 even though it contains a null. pandas would convert that column to float64 so it could hold NaN. In Polars every dtype can hold nulls, so integer columns keep their type. Validity is tracked separately from the values.
Dtype mapping from pandas
| pandas dtype | Polars dtype | Notes |
|---|---|---|
| `int64`, `int32`, ... | `Int64`, `Int32`, ... | Also `UInt8` to `UInt64`. |
| `float64` | `Float64` | `Float32` is available. |
| `bool` | `Boolean` | Can contain null without becoming `object`. |
| `object` (strings) | `String` | Backed by Arrow UTF-8 data. `Utf8` is an old alias. |
| `object` (mixed) | `Object` or an error | Avoid `Object`. Most operations do not work on it. |
| `category` | `Categorical` or `Enum` | `Enum` has a fixed, ordered set of categories. |
| `datetime64[ns]` | `Datetime("us")` by default | Pass `"ns"` or `"ms"` to choose the unit. |
| `timedelta64` | `Duration` | Also has a time unit. |
| (none) | `Date`, `Time` | Calendar date and time of day. |
| lists in `object` | `List`, `Array` | Typed, nested columns. |
| dicts in `object` | `Struct` | Named fields, each with its own dtype. |
The biggest change is object. In pandas, object is a catch-all that often hides strings, mixed numbers and Python objects. Polars wants one concrete dtype per column. If a column holds mixed types, Polars raises an error or asks you to choose a dtype, and that is the right moment to clean the data.
Setting dtypes when you read data
pandas infers dtypes from the data and lets you override them with dtype=. Polars infers from the first rows, 100 by default, and you override with schema_overrides. If a column's type only becomes clear after the sample, the read can fail or choose the wrong type.
import io
import polars as pl
csv = io.StringIO(
"order_id,zip,price,placed_at\n"
"1,02134,9.5,2026-01-05\n"
"2,10001,3.0,2026-01-06\n"
)
df = pl.read_csv(
csv,
schema_overrides={"zip": pl.String, "order_id": pl.Int32},
try_parse_dates=True,
)
print(df.schema)The override on zip keeps the leading zero in 02134. Without it, Polars would infer an integer and the zero would be lost. try_parse_dates=True turns placed_at into a Date.
Two other read options matter when you port code:
infer_schema_length=Nonescans the whole file before choosing types. It is slower but safer for messy files.schema=replaces inference entirely. You list every column, and the file must match.
Casting
Use cast where you would use astype. The main difference is that cast is strict by default. A value that cannot be converted raises an error instead of producing a surprise.
import polars as pl
raw = pl.DataFrame({"qty": ["1", "2", "x"]})
try:
raw.with_columns(pl.col("qty").cast(pl.Int64))
except pl.exceptions.PolarsError as err:
print("strict cast failed:", type(err).__name__)
clean = raw.with_columns(pl.col("qty").cast(pl.Int64, strict=False))
print(clean["qty"].to_list()) # [1, 2, None]With strict=False, failed conversions become null. This resembles pd.to_numeric(..., errors="coerce"), except the failures become null instead of NaN. Count them before you move on:
bad = clean["qty"].null_count() - raw["qty"].null_count()
print(bad) # 1Strict casting also protects you when you shrink integer types. Casting 300 to Int8 raises an error with the default settings. It does not wrap around.
Categorical and Enum
pandas category is often used to save memory or to control sort order. Polars has two replacements:
Categoricalis created from the values you provide. It suits columns where the set of values is not known up front.Enumhas a fixed list of allowed values, in a fixed order. Values outside the list raise an error.
import polars as pl
sizes = pl.Enum(["small", "medium", "large"])
s = pl.Series("size", ["large", "small", "medium"], dtype=sizes)
print(s.sort().to_list()) # ['small', 'medium', 'large']Sorting follows the order you declared, so Enum is the closest match for an ordered pandas CategoricalDtype.
Datetimes and time units
pandas stores timestamps as nanoseconds by default. Polars defaults to microseconds. Your data keeps its meaning, but a round trip through Polars can change the unit. This matters when you compare frames or write Parquet files that other tools read. If you need nanoseconds, request them:
import polars as pl
df = pl.DataFrame({"ts": ["2026-01-05 10:00:00"]}).with_columns(
pl.col("ts").str.to_datetime(time_unit="ns", time_zone="UTC")
)
print(df.schema) # ts: Datetime(time_unit='ns', time_zone='UTC')The time zone is part of the dtype. A naive Datetime and a Datetime with a zone are different dtypes, and Polars will not silently mix them.
Inspecting and checking schemas
Use selectors to work on dtype groups. They replace select_dtypes.
import polars as pl
import polars.selectors as cs
df = pl.DataFrame({"a": [1, 2], "b": [0.5, 1.5], "c": ["x", "y"]})
print(df.select(cs.numeric()).columns) # ['a', 'b']Lazy frames need one extra step. Reading .schema on a LazyFrame can be costly because Polars must resolve the plan, and recent versions warn about it. Call collect_schema() instead:
lazy = pl.LazyFrame({"a": [1, 2]})
print(lazy.collect_schema())Because a schema is just a mapping, you can assert it at the boundaries of your code. This catches dtype drift early during a migration:
EXPECTED = {"order_id": pl.Int32, "zip": pl.String, "price": pl.Float64}
def check_schema(frame: pl.DataFrame) -> None:
actual = {name: frame.schema[name] for name in EXPECTED if name in frame.schema}
if actual != EXPECTED:
raise TypeError(f"unexpected schema: {frame.schema}")Common errors
- Leading zeros lost. Identifier columns read as integers. Override them to
String. - Mixed-type columns. A column that mixes numbers and text fails to parse. Read it as
String, then clean and cast. - Integer division surprises. Dividing two integer columns with
/gives aFloat64. Use//for integer results, as in Python. - Comparing frames with different units. A
Datetime("ns")and aDatetime("us")column are different dtypes. Cast one before comparing.
Exercise
A CSV has a column account with values like 007 and 120. Polars reads it as Int64 and shows 7 and 120. How do you fix this when reading, and what dtype should the column have?
Show answer
Pass schema_overrides={"account": pl.String} to pl.read_csv. The column then has dtype String, and 007 keeps its leading zeros. Cast to an integer only if you do not need the zeros.
Exercise
A pandas column of integers with missing values became float64. What dtype does Polars give the same data, and how do missing values appear?
Show answer
Polars keeps Int64. Missing values are stored as null, not NaN, so no float conversion is needed.