Sub topic 10
Checking that downcasting preserved your data
This chapter assumes you can downcast columns with pd.to_numeric and convert strings to category. It also assumes you know the basic NumPy dtypes. Downcasting makes columns smaller, but a smaller dtype can change your values. You need to confirm that it didn't.
Where values can change
Integers and floats fail in different ways.
- Integers are exact or wrong.
pd.to_numeric(..., downcast="integer")picks a dtype that holds every value in the column, so it is safe. A manualastype("int8")is not safe. NumPy wraps out-of-range values around without raising an error. - Floats lose precision.
float32keeps about 7 significant digits, whilefloat64keeps about 15 to 16. Small relative errors (around 1e-7) are usual. Very large values lose whole units. - Categories keep the strings. The risks are in later operations, such as grouping, which the last section covers.
import numpy as np
values = np.array([100, 200, 300], dtype="int64")
print(values.astype("int8")) # [100 -56 44]
print(np.float32(16_777_217)) # 16777216.0The first line shows silent wraparound. The second shows that float32 cannot represent every integer above 2**24.
A verification routine
The check below compares the structure first. Then it compares each column in the way that suits its type. It compares integers exactly and floats with a relative tolerance. It compares everything else after converting both sides to object, so a category column can be compared with the original strings. Series.equals treats missing values in the same positions as equal.
import numpy as np
import pandas as pd
from pandas.api.types import is_float_dtype, is_integer_dtype
def check_shrink(original, shrunk, rtol=1e-6):
assert original.shape == shrunk.shape, "shape changed"
assert original.columns.equals(shrunk.columns), "columns changed"
assert original.index.equals(shrunk.index), "index changed"
for col in original.columns:
a, b = original[col], shrunk[col]
if is_integer_dtype(a):
ok = np.array_equal(a.to_numpy(), b.to_numpy())
elif is_float_dtype(a):
ok = np.allclose(
a.to_numpy(), b.to_numpy(dtype="float64"),
rtol=rtol, equal_nan=True,
)
else:
ok = a.astype(object).equals(b.astype(object))
assert ok, f"column {col!r} changed"
print("all columns match")
rng = np.random.default_rng(0)
n = 1_000
df = pd.DataFrame({
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR"], n),
})
shrunk = df.copy()
shrunk["age"] = pd.to_numeric(shrunk["age"], downcast="integer")
shrunk["score"] = pd.to_numeric(shrunk["score"], downcast="float")
shrunk["country"] = shrunk["country"].astype("category")
check_shrink(df, shrunk)
bad = shrunk.copy()
bad["age"] = bad["age"] + 1
try:
check_shrink(df, bad)
except AssertionError as err:
print("caught:", err)The first call prints all columns match. The second call, on deliberately altered data, prints caught: column 'age' changed. This shows the check can fail.
Choosing a tolerance
The rtol=1e-6 argument means each value may differ from the original by one part in a million. float32 rounding stays well below that. If your data needs more precision, such as money amounts or large identifiers, keep float64. Never downcast values that you later compare for exact equality.
Checking results, not just values
Floats can pass the per-value check and still drift when you add many of them. A float32 sum accumulates rounding error, so compare the aggregates your analysis depends on.
before = df.groupby("country")["score"].mean()
after = shrunk.groupby("country", observed=True)["score"].mean()
print(np.allclose(before.to_numpy(), after.to_numpy(), rtol=1e-5))This prints True. Both results are sorted by country, so the arrays line up.
Pass observed=True when you group by a categorical column. Without it, pandas can return a row for every declared category, including ones that never appear in the data. Those rows hold empty results, which can cause surprises later.
Memory is part of the check
Also confirm that the change saved memory. If it didn't, the extra risk bought nothing.
print(df.memory_usage(deep=True).sum(), shrunk.memory_usage(deep=True).sum())Exercise
A colleague shrinks a column with df["views"].astype("int8") and finds no errors. Why is that not enough, and which check would catch a problem?
Show answer
NumPy-style casting wraps out-of-range values silently (200 becomes -56), so no error is raised. Compare the original and shrunk columns with an exact check such as np.array_equal(original.to_numpy(), shrunk.to_numpy()). Using pd.to_numeric(..., downcast="integer") avoids the problem because it chooses a dtype that fits.