Sub topic 5
Setting data types at load time
This chapter assumes you can call pd.read_csv and know what a DataFrame and a dtype are. It covers how pandas picks column types, where that goes wrong, and how to set types as the file loads.
What inference does
By default, read_csv looks at the text in each column and picks a type. A column that looks like whole numbers becomes int64. A column with decimals becomes float64. Anything else becomes object, which holds Python strings.
Inference is convenient, but it can destroy information.
import pandas as pd
from io import StringIO
text = "zip,city,qty\n02134,Boston,5\n10001,New York,7\n"
df = pd.read_csv(StringIO(text))
print(df.dtypes)
print(df["zip"].tolist())The zip codes load as int64, and the list prints [2134, 10001]. The leading zero is gone, and converting back to text will not restore it. Identifiers such as zip codes, phone numbers and account numbers should be read as text.
Declaring types with dtype
Pass a dictionary to dtype that maps column names to types.
import pandas as pd
from io import StringIO
text = "zip,city,qty\n02134,Boston,5\n10001,New York,7\n"
df = pd.read_csv(
StringIO(text),
dtype={"zip": "string", "city": "category", "qty": "int32"},
)
print(df.dtypes)
print(df["zip"].tolist())The zip codes now load as ['02134', '10001']. Columns you leave out of the dictionary are still inferred.
| Type name | Use it for | Notes |
|---|---|---|
| `"string"` | Identifiers, free text | Keeps leading zeros. Supports missing values. |
| `"category"` | Columns with few distinct values | Saves memory on repeated labels. |
| `"int32"`, `"float32"` | Numbers with a known small range | Halves memory compared with 64-bit types. |
| `"Int64"` | Integers that may be missing | Capital `I`. Stores missing values as `<NA>`. |
| `"boolean"` | True/False that may be missing | Nullable counterpart of `bool`. |
Integers with missing values
NumPy integers cannot represent a missing value. If an integer column has a blank cell, inference converts the whole column to float64, and 4 becomes 4.0. The nullable Int64 type avoids this.
import pandas as pd
from io import StringIO
text = "id,visits\n1,4\n2,\n3,9\n"
inferred = pd.read_csv(StringIO(text))
print(inferred["visits"].dtype)
nullable = pd.read_csv(StringIO(text), dtype={"visits": "Int64"})
print(nullable["visits"].dtype)
print(nullable["visits"].tolist())The first dtype is float64. The second is Int64, and the list is [4, <NA>, 9].
Common errors
- ValueError when casting. If you declare
"int64"for a column that has blanks or text such as"abc",read_csvraises aValueError. Use"Int64"for blanks. For stray text, find the bad values first or read the column as"string"and clean it. - DtypeWarning about mixed types. On large files pandas may infer types in pieces, so one column ends up with both numbers and strings. Declare the column's
dtypeto remove the warning and get one consistent type. - A misspelled column name. Keys in
dtypethat match no column do not raise an error. The setting is silently ignored. Check the result withdf.dtypes.
For per-column cleanup while reading, converters={"col": func} runs a function on each cell. It is slower than dtype, so use it only when a plain type cannot express the fix.
Exercise
A CSV column visits holds whole numbers, but some cells are empty. Which dtype setting keeps the values as integers instead of converting them to floats, and why does the default not do this?
Show answer
Use dtype={"visits": "Int64"}. The default NumPy int64 cannot store missing values, so inference converts the column to float64 to hold NaN. The nullable Int64 type stores missing cells as <NA> and keeps the other values as integers.