Sub topic 3
Keeping Missing Values with Nullable dtypes
Assume you know basic Python, can create and index pandas objects, and can read CSV files. This chapter focuses on preserving missing values while choosing useful column types.
Nullable dtypes
Traditional NumPy integer columns cannot store a missing value. Pandas may therefore convert an integer column to float64, because NaN is a floating-point value. Pandas nullable dtypes avoid this problem:
Int64stores integers andpd.NA.booleanstoresTrue,False, andpd.NA.stringstores text andpd.NA.
pd.NA is pandas' missing-value marker. Use isna() to find it rather than comparing values directly.
import io
import pandas as pd
raw = pd.DataFrame({
"qty": ["3", None, "7"],
"answer": ["yes", "no", None],
"status": ["new", "shipped", "new"],
})
raw["qty"] = pd.to_numeric(raw["qty"], errors="coerce").astype("Int64")
raw["answer"] = raw["answer"].map({"yes": True, "no": False}).astype("boolean")
raw["status"] = raw["status"].astype("category")
csv = io.StringIO(
"zip,status,order_date\n"
"02134,shipped,2024-01-05\n"
"10001,pending,2024-01-06\n"
)
orders = pd.read_csv(
csv,
dtype={"zip": "string", "status": "category"},
parse_dates=["order_date"],
)
print(raw.dtypes)
print(orders.dtypes)Mapping yes/no values is safer than using astype(bool). In Python, the string "no" is truthy, so astype(bool) would incorrectly produce True.
Repeated labels and automatic conversion
The category dtype stores repeated labels as codes plus a shared list of categories. It can reduce memory use and make the intended domain clear. Use it when a column has relatively few repeated values. Avoid it for nearly unique values.
convert_dtypes() asks pandas to replace older types with suitable nullable types. It is useful after loading or combining data, but inspect the result rather than assuming every choice is appropriate.
flowchart TD
A[Read data] --> B[Set explicit dtypes]
B --> C[Convert remaining columns]
C --> D[Validate missing values]Control memory deliberately
pd.to_numeric(series, downcast="integer") selects a smaller integer type when its values fit. Check memory before and after with memory_usage(deep=True). Downcasting can save memory, but future values may exceed the smaller type's range.
> callout note > Nullable dtypes preserve missingness without forcing integer data to become floating point.
Exercise
Why should you map "yes" and "no" before converting a column to boolean?
Show answer
Because every non-empty string, including "no", is truthy when converted directly with astype(bool).