Sub topic 10
Checking that downcasting preserved your data
This chapter assumes you can already downcast columns with pd.to_numeric and convert strings to category. It covers how to confirm that the smaller DataFrame still holds the same data, and which later operations can break values that looked fine.
Why shrinking needs a check
Downcasting changes how each value is stored, not what it means. Three things can go wrong:
- A value does not fit the new type. This is rare with
pd.to_numeric, which only picks a type that holds the current values. It is common with a hand-writtenastype. - Precision is lost. Float32 keeps about 7 significant decimal digits, and float64 keeps about 15 to 16.
- Later operations misbehave. New data, arithmetic, or grouping can hit the limits of the smaller type.
The first two problems can be caught with a comparison right after the conversion. The third needs guards in the code that runs afterwards.
| Conversion | Typical risk | How to check |
|---|---|---|
| int64 to int8, int16, int32 | Overflow with `astype`, or later arithmetic wraps around | Exact equality, plus a range check before converting |
| int64 to unsigned | Negative values wrap to large numbers | Exact equality, check `min() >= 0` |
| float64 to float32 | About 7 digits of precision, rounding in sums | `np.allclose` with a stated tolerance |
| int64 to float32 | Integers above 16,777,216 lose exactness | Exact equality after converting back |
| object to category | Unused categories, new values, unexpected group output | Convert back and compare, test the downstream operations |
Exact checks for integers
Integers are stored exactly, so any difference at all is a bug. Compare against the original after casting back to its dtype.
import numpy as np
import pandas as pd
original = pd.Series([34, 29, 41, 300], dtype="int64")
safe = pd.to_numeric(original, downcast="integer")
print(safe.dtype) # int16
print(original.equals(safe.astype(original.dtype))) # True
unsafe = original.astype("int8") # forced, no range check
print(unsafe.tolist()) # 300 wraps around to 44
print(original.equals(unsafe.astype(original.dtype))) # Falseto_numeric chose int16 because 300 does not fit in int8. The forced astype("int8") raised no error. NumPy wraps the value around, so 300 becomes 44.
Use Series.equals here rather than (a == b).all(). It checks that the index and values match, and it treats missing values in the same position as equal.
Check the range before you force a type
If you pick a dtype yourself, for example from a data dictionary, test the range first.
def fits(series, dtype):
info = np.iinfo(dtype)
return series.min() >= info.min and series.max() <= info.max
print(fits(original, "int8")) # False, because of 300
print(fits(original, "int16")) # Truenp.iinfo reports the smallest and largest value of an integer dtype. It works only for integer types. Use np.finfo for floats.
Tolerance checks for floats
Float32 rounds every value to the nearest representable number. For a value near 1, the spacing between neighbours is about 6e-8, so the stored value can be up to about 3e-8 away from the original. In relative terms the error is at most about 6e-8, whatever the magnitude.
Because exact equality will fail, compare with a tolerance:
rng = np.random.default_rng(0)
scores = pd.Series(rng.random(100_000))
small = pd.to_numeric(scores, downcast="float")
print(small.dtype) # float32
as64 = small.astype("float64")
print(scores.equals(as64)) # False, expected
print(np.allclose(scores, as64, rtol=1e-6, equal_nan=True)) # True
rel_err = ((scores - as64).abs() / scores).max()
print(rel_err < 6e-8) # Truenp.allclose(a, b, rtol, atol) passes when |a - b| <= atol + rtol * |b| for every element. The default atol is 1e-8. If your column holds values very close to zero, choose atol deliberately instead of relying on that default. equal_nan=True treats missing values in the same position as equal. Without it, any NaN makes the check fail.
Choose the tolerance from what the data is used for. A model feature can usually tolerate 1e-6. Currency amounts, coordinates for precise geometry, and anything that gets summed over millions of rows may not.
Integers that become floats
Float32 has a 24-bit significand, so it holds integers exactly only up to 16,777,216 (2 to the 24th power). Large identifiers are the usual victim.
ids = pd.Series([16_777_216, 16_777_217], dtype="int64")
print(ids.astype("float32").tolist()) # [16777216.0, 16777216.0]Two different IDs now look identical. Never turn identifier columns into floats, even when the data looks numeric.
A single verification function
Write the checks once and run them on every conversion. This function returns the list of columns that differ.
def check_same(original, shrunk, rtol=1e-6):
bad = []
if not original.index.equals(shrunk.index):
bad.append("index changed")
if list(original.columns) != list(shrunk.columns):
bad.append("columns changed")
return bad
for col in original.columns:
a, b = original[col], shrunk[col]
if a.dtype.kind == "f":
ok = np.allclose(a.to_numpy("float64"), b.to_numpy("float64"),
rtol=rtol, equal_nan=True)
else:
ok = a.equals(b.astype(a.dtype))
if not ok:
bad.append(col)
return badFor float columns it uses a tolerance. For every other column, including categoricals, it converts back to the original dtype and demands an exact match. The function assumes plain NumPy-backed float columns. Nullable float dtypes that contain pd.NA need converting first, for example with to_numpy("float64", na_value=np.nan).
Now run it on the sample DataFrame, once with proper conversions and once with a deliberate mistake.
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
})
shrunk = df.copy()
shrunk["user_id"] = pd.to_numeric(shrunk["user_id"], downcast="unsigned")
shrunk["age"] = pd.to_numeric(shrunk["age"], downcast="integer")
shrunk["score"] = pd.to_numeric(shrunk["score"], downcast="float")
shrunk["country"] = shrunk["country"].astype("category")
print(shrunk.dtypes.to_dict())
print(check_same(df, shrunk)) # []
broken = shrunk.copy()
broken["user_id"] = df["user_id"].astype("int8") # most IDs exceed 127
print(check_same(df, broken)) # ['user_id']An empty list means every column matched. Keep the final comparison as an assert in pipelines so a failure stops the job instead of passing bad data along:
assert not check_same(df, shrunk), "downcasting changed the data"The verification workflow
Problems that appear after conversion
A passing comparison proves the data is intact now. It does not protect later operations.
Arithmetic wraps silently
Integer arithmetic stays in the narrow type. If the result no longer fits, it wraps around with no warning.
ages = pd.Series([34, 29, 41, 90], dtype="int8")
print((ages + 100).tolist()) # [-122, -127, -115, -66]
print((ages.astype("int64") + 100).tolist()) # [134, 129, 141, 190]Widen a column before you compute with it, as in the second line. Do the same before multiplying, squaring, or accumulating running totals.
New data may not fit
A dtype chosen for today's file can be too small for next month's. When you append or concatenate fresh data, run the fits check, or let to_numeric pick the type again from the combined values. In a pipeline, a fixed dtype map should be paired with a range check at load time so that an out-of-range value raises an error.
Float32 sums and means
Aggregates over many float32 values accumulate rounding error. Compare an aggregate computed on both versions, and use a tolerance that suits your use:
a = df["score"].mean()
b = shrunk["score"].mean()
print(np.isclose(a, b, rtol=1e-5))If the check fails, run the aggregate on shrunk["score"].astype("float64").
Categorical grouping
A categorical column keeps its full list of categories even when some have no rows. If you filter and then group, the empty categories can appear in the result.
subset = shrunk[shrunk["country"].isin(["US", "DE"])]
print(subset.groupby("country", observed=False)["score"].size())
print(subset.groupby("country", observed=True)["score"].size())The first call lists all five countries and shows 0 for the three that were filtered out. The second lists only DE and US. Pass observed=True explicitly so the result does not depend on which pandas version is installed. The default has changed between versions.
What a check can and cannot prove
The comparison covers the data you have. It cannot tell you that the next batch will fit, that your downstream code never exceeds the narrow type, or that a tolerance is acceptable for your analysis. Treat it as a gate for each conversion, then keep range checks and widening steps in the code that uses the data.
Exercise
A column of order totals holds float64 values such as 19.99 and 1204.5. You convert it with downcast="float" and want to confirm the result. Why does original.equals(small.astype("float64")) return False, and which check should you use instead?
Show answer
Float32 stores each value rounded to about 7 significant digits, so casting back to float64 gives numbers that differ slightly from the originals (19.99 is not exactly representable in either type, and the two rounded forms differ). equals demands identical values. Use np.allclose(original, small.astype("float64"), rtol=1e-6, equal_nan=True), with a tolerance suited to how the totals are used. If the totals must be exact, for example for accounting, keep float64 or store cents as integers.
Exercise
You store age as int8 and later run df["age_in_days"] = df["age"] * 365. The values come out wrong and some are negative. What happened, and how do you fix it?
Show answer
The multiplication stays in int8, whose range is -128 to 127. Results such as 34 365 exceed that range and wrap around silently. Widen before computing, for example `df["age"].astype("int32") 365`, which holds values up to about 2.1 billion. Then store the result in a dtype chosen for its own range.
Exercise
After filtering a categorical country column down to two countries, groupby("country")["score"].mean() returns five rows, three with NaN. How do you get only the two countries that are present?
Show answer
The filtered column still lists all five categories, and grouping with observed=False includes the empty ones. Pass observed=True: subset.groupby("country", observed=True)["score"].mean(). Alternatively, call subset["country"].cat.remove_unused_categories() first.