Sub topic 2
Data types and reading a schema
This chapter assumes you can write basic Python and have met DataFrames and Series. Every column in a Polars DataFrame has exactly one data type (dtype). The collection of column names and dtypes is the schema. Most surprises in Polars code, such as a failed join or a column that is a string when you expected a number, show up first in the schema.
Reading a schema
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
print(df.schema)
print(df.dtypes)
print(df.columns)df.schema maps each column name to its dtype. Here name and dept are String and salary is Int64. df.dtypes and df.columns give the two halves as lists. Polars infers dtypes from the Python values: ints become Int64, floats become Float64, strings become String.
Common dtypes
| Family | Dtypes | Notes |
|---|---|---|
| Integer | `Int8` to `Int64`, `UInt8` to `UInt64` | Smaller types use less memory but can overflow. |
| Float | `Float32`, `Float64` | `Float64` is the default for decimals. |
| Text | `String`, `Categorical` | `Categorical` suits columns with few distinct values. |
| Logical | `Boolean` | Results of comparisons. |
| Time | `Date`, `Datetime`, `Duration` | Covered in the namespaces chapter. |
| Nested | `List`, `Struct` | A column whose cells hold lists or records. |
Setting dtypes explicitly
Inference is convenient, but you can state the schema yourself. This also fixes the dtype when the data is empty or ambiguous.
typed = pl.DataFrame(
{"name": ["Ana", "Ben"], "salary": [120, 100]},
schema={"name": pl.String, "salary": pl.Float32},
)
print(typed.schema)Converting with cast
To change a dtype after the fact, use the cast expression inside a context such as with_columns.
converted = df.with_columns(
pl.col("salary").cast(pl.Int32),
pl.col("dept").cast(pl.Categorical),
)
print(converted.schema)Arithmetic can change dtypes too. In the first chapter's example, pl.col("salary") * 1.1 turns an Int64 column into Float64.
Casting failures
By default cast is strict. If a value cannot be converted, Polars raises an error. Passing strict=False turns those values into null instead.
raw = pl.Series("amount", ["10", "25", "n/a"])
print(raw.cast(pl.Int64, strict=False))The result is [10, 25, null].
Common errors
- Mixed types in one column. A list like
[1, "two"]cannot become one dtype, so Polars raises an error or falls back to a more general type. Clean the input first. - Joining on mismatched dtypes. An
Int32key will not join to anInt64key until you cast one side. - Integer overflow. Casting down to
Int8orUInt8on large values fails in strict mode. - Reading numbers as strings. One stray text value makes a CSV column
String. Checkschemaright after loading.
Exercise
A column age was read as String because one row contains "unknown". Write an expression, used inside with_columns, that converts it to Int64 and turns "unknown" into null. Why is strict=False risky here?
Show answer
Use df.with_columns(pl.col("age").cast(pl.Int64, strict=False)). It is risky because every value that fails to convert silently becomes null, not only "unknown". Typos and corrupted values disappear without any error, so compare the null counts before and after the cast.