Sub topic 2
Data types and reading a schema
Every Polars column has exactly one data type, called a dtype. The dtypes of all columns together form the schema. This chapter covers how to read a schema, how Polars picks dtypes, how to choose them yourself, and which mistakes cause trouble later. It assumes you know the DataFrame and Series containers from the previous chapter and can read basic Python.
Why dtypes matter
Polars stores each column as a typed, contiguous block of memory. Because of that, an expression like pl.col("salary") * 1.1 is checked against the dtype of salary before it runs, and the result dtype is known in advance. A column never holds a mix of types. If one value cannot fit the dtype, Polars raises an error or stores a null.
The dtype also decides memory use, which operations are allowed, and how values are displayed. A column of dates supports date arithmetic, and a column of strings does not.
Reading a schema
A DataFrame exposes its schema in several ways.
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) # ordered mapping: column name -> dtype
print(df.columns) # ['name', 'dept', 'salary']
print(df.dtypes) # [String, String, Int64]
print(df.width, df.height)
print(df.schema["salary"] == pl.Int64) # Truedf.schema is an ordered mapping from column name to dtype. It prints as Schema({'name': String, 'dept': String, 'salary': Int64}). The exact wrapper text varies between Polars versions, but the names and dtypes are the same. You can index it like a dictionary and compare entries to dtype classes such as pl.Int64.
Reading the schema is the quickest way to find a type problem. If a column you expect to be numeric shows String, every arithmetic expression on it will fail.
Default inference
When you build a DataFrame from Python objects, Polars infers dtypes from the values.
| Python value | Inferred dtype |
|---|---|
| `int` | `Int64` |
| `float` | `Float64` |
| `str` | `String` |
| `bool` | `Boolean` |
| `datetime.date` | `Date` |
| `datetime.datetime` | `Datetime` (microsecond precision) |
| `datetime.timedelta` | `Duration` |
| `list` | `List(inner dtype)` |
| `dict` | `Struct` |
| `None` only | `Null` |
A column containing only None gets the dtype Null, which is rarely what you want. If a column of missing values will later hold numbers, give it an explicit dtype.
The main dtype families
- Integers.
Int8,Int16,Int32andInt64are signed.UInt8throughUInt64are unsigned. The number is the bit width, so anInt8holds -128 to 127. - Floats.
Float32andFloat64. These are the only dtypes that can holdNaN. Decimal. Fixed-point numbers for exact values such as money. Its support is still marked unstable in some versions, so check the documentation for your release.String. Text. Older code and documentation call itUtf8, which is an alias.CategoricalandEnum. Both store repeated strings as integer codes plus a lookup table.Categoricalgrows its set of categories as data arrives.Enumhas a fixed list you declare up front, and values outside it raise an error.Date,Datetime,Time,Duration.Datetimecarries a time unit ("ms","us"or"ns") and an optional time zone, for examplepl.Datetime("us", "UTC").List,Array,Struct. AListholds a variable number of values of one inner dtype. AnArrayhas a fixed length. AStructgroups named fields in one column.
Nested dtypes show their contents in the schema:
nested = pl.DataFrame(
{
"tags": [["a", "b"], ["c"]],
"point": [{"x": 1, "y": 2}, {"x": 3, "y": 4}],
}
)
print(nested.schema)
# tags is List(String), point is Struct({'x': Int64, 'y': Int64})Choosing dtypes yourself
You can fix the schema when you construct a DataFrame. The schema argument sets the dtype for each column.
scores = pl.DataFrame(
{"id": [1, 2, 3], "score": [1.5, None, 3.0]},
schema={"id": pl.UInt32, "score": pl.Float32},
)
print(scores.schema)To change dtypes on an existing DataFrame, use cast inside an expression:
smaller = df.with_columns(
pl.col("salary").cast(pl.Int16),
pl.col("dept").cast(pl.Categorical),
)
print(smaller.schema)Choosing a narrower integer or a categorical for a column with few distinct values reduces memory use. Int16 takes a quarter of the memory of Int64. A categorical stores each distinct string once instead of repeating it on every row.
The same applies when reading files. The CSV reader infers dtypes from the first rows (100 by default, set by infer_schema_length). You can override specific columns with schema_overrides. Older versions called this argument dtypes.
import io
text = "id,zip,amount\n1,02134,10.5\n2,90210,7.25\n"
orders = pl.read_csv(io.StringIO(text), schema_overrides={"zip": pl.String})
print(orders.schema)Without the override, zip would be read as an integer and the leading zero in 02134 would be lost.
Casting: strict and non-strict
By default cast is strict. If any value cannot be converted, Polars raises an error instead of guessing. With strict=False, those values become null.
raw = pl.DataFrame({"qty": ["3", "7", "n/a"]})
try:
raw.with_columns(pl.col("qty").cast(pl.Int64))
except pl.exceptions.PolarsError:
print("strict cast failed on 'n/a'")
print(raw.with_columns(pl.col("qty").cast(pl.Int64, strict=False)))The second call returns 3, 7 and null.
Arithmetic and result dtypes
The dtype of a result follows from the dtypes of the inputs. Some rules are worth memorizing:
- Integer
+,-and*give an integer. Integer with float gives a float, sosalary * 1.1isFloat64. - The
/operator always returns a float, even for two integers. Use//for floor division that stays integer. - Mixing signed and unsigned integers promotes to a wider signed type where needed.
You can verify this on a small example without guessing:
check = df.select(
(pl.col("salary") / 12).alias("true_div"),
(pl.col("salary") // 12).alias("floor_div"),
)
print(check.schema) # true_div is Float64, floor_div is Int64Null is not NaN
Every dtype can hold null, which means "missing". Only floats can also hold NaN, which means "not a number". They are different values and behave differently.
s = pl.Series("x", [1.0, None, float("nan")])
print(s.is_null().to_list()) # [False, True, False]
print(s.is_nan().to_list()) # [False, None, True]is_nan returns null for the null entry, because the question has no answer for a missing value. Integer columns have no NaN, so a missing integer is always null. A later chapter covers null handling in detail. For now, remember that the schema does not change when nulls appear. An Int64 column with nulls is still Int64.
Common errors
- A numeric column read as
String. One stray value such as"n/a"makes the CSV reader treat the whole column as text. Check the schema right after reading, then cast withstrict=Falseor fix the source. - A column typed
Null. All values wereNone. Give the column an explicit dtype. - Comparing a dtype to a string. Use
df.schema["x"] == pl.Int64, not== "Int64". - Silent precision loss. Casting
Float64toFloat32or to an integer drops precision or truncates, and neither raises an error. - Overflow surprises. Computing with
Int8orUInt8columns can exceed the range. Keep wide dtypes for calculation, and narrow only for storage.
Exercise
A CSV file has a column code with values such as 007, 042 and 310. After pl.read_csv, the column shows as Int64 and the leading zeros are gone. How do you keep the original text, and how would you confirm the fix?
Show answer
Pass schema_overrides={"code": pl.String} to pl.read_csv so the column is read as text. Then print df.schema (or check df.schema["code"] == pl.String) to confirm the dtype is String and that values like 007 appear unchanged.
Exercise
You run pl.DataFrame({"n": ["1", "2", "x"]}).with_columns(pl.col("n").cast(pl.Int64, strict=False)). What dtype does n have afterwards, and what is the value on the third row?
Show answer
The dtype is Int64, and the third row is null, because "x" cannot be converted and the non-strict cast turns failed conversions into null.