Sub topic 4
Downcasting floats and what precision you give up
Float columns are the second place to look for memory savings, after integers. A float64 column uses 8 bytes per value. A float32 column uses 4 bytes per value and holds fewer significant digits. This chapter explains what that trade costs, how pd.to_numeric(..., downcast="float") behaves, and how to check a cast before you keep it.
This chapter assumes you can create DataFrames, read df.dtypes, and use memory_usage(deep=True) as in the earlier chapters. It also assumes you know that NumPy stores each column as a fixed-width array.
How floating-point types store numbers
A floating-point value is stored as a sign, an exponent, and a mantissa (the significant digits). The exponent sets the scale. The mantissa sets how finely values can be told apart at that scale. Fewer bytes mean fewer mantissa bits, so each value is only approximate.
| dtype | Bytes | Mantissa bits | Reliable decimal digits | Largest finite value |
|---|---|---|---|---|
| float16 | 2 | 10 | about 3 | 65,504 |
| float32 | 4 | 23 | about 6 to 7 | about 3.4e38 |
| float64 | 8 | 52 | about 15 to 16 | about 1.8e308 |
Print these limits from NumPy instead of memorizing them:
import numpy as np
for t in (np.float16, np.float32, np.float64):
info = np.finfo(t)
print(t.__name__, info.bits // 8, "bytes", info.precision, "digits", info.max, info.eps)eps is the gap between 1.0 and the next representable number. For float32 it is about 1.2e-7. That is a relative gap, so the absolute gap grows with the magnitude of the value.
Precision depends on magnitude
A float32 value keeps about seven significant digits wherever the value sits on the number line. Small values keep fine detail. Large values lose it. Above 2**24 (16,777,216) a float32 can no longer represent every integer:
import numpy as np
x = np.array([16_777_216.0, 16_777_217.0])
print(x.astype(np.float32)) # [16777216. 16777216.]
print(np.float32(1_700_000_001)) # 1700000000.0
print(float(np.float32(0.1))) # 0.10000000149011612The second line shows why Unix timestamps in seconds (about 1.7 billion) are a poor fit for float32. At that size the gap between neighboring values is 128. The third line shows that a decimal fraction such as 0.1 is already inexact in binary. In float32 the error is larger than in float64.
Downcasting with pd.to_numeric
The downcast="float" option asks pandas for a smaller float type:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"score": rng.random(n),
"price": rng.random(n) * 1000,
})
before = df.memory_usage(deep=True).sum()
for col in ["score", "price"]:
df[col] = pd.to_numeric(df[col], downcast="float")
after = df.memory_usage(deep=True).sum()
print(df.dtypes)
print(before, after)Both columns become float32, and the total drops by almost half. The small remainder is the index, which does not shrink.
Four details of this function matter in practice:
float32is the floor.downcast="float"never producesfloat16. If you wantfloat16, you must callastype("float16")yourself, and you should have a strong reason.- It never produces an integer dtype. A float column holding
1.0, 2.0, 3.0stays a float. Usedowncast="integer"on such a column only after you have decided it really holds whole numbers. - It downcasts only when the values pass a tolerance check. If the cast changes values by more than the tolerance, pandas keeps
float64. The tolerance is absolute, not relative, and it is loose enough that a pass does not prove your precision needs are met. Treat the check as a guard against gross loss, and run your own check as shown below. - It does not change integer-like data stored as floats because of
NaN. If a column is float only because it contains missing values, consider the nullableInt64dtype instead.
Measuring what you lose
Before keeping a cast, measure the error. This helper casts to float32 and reports absolute error, relative error, overflow, and whether NaN positions survive:
import numpy as np
import pandas as pd
def float32_report(s: pd.Series) -> pd.Series:
small = s.astype("float32")
diff = (s - small.astype("float64")).abs()
rel = diff / s.abs().where(s != 0)
overflowed = (np.isinf(small) & ~np.isinf(s)).any()
return pd.Series({
"max_abs_err": diff.max(),
"max_rel_err": rel.max(),
"overflowed": bool(overflowed),
"nan_preserved": bool(small.isna().equals(s.isna())),
})
rng = np.random.default_rng(1)
scores = pd.Series(rng.random(1000) * 100)
stamps = pd.Series([1_700_000_001.0, 1_700_000_050.0, 1_700_000_123.0])
print(float32_report(scores))
print(float32_report(stamps))For scores, the relative error stays near 1e-7, which is the expected float32 limit. For stamps, the maximum absolute error is 50.0 seconds. The relative error is still tiny, about 3e-8, which is why you must look at the absolute error when the unit matters. A relative error of 3e-8 is acceptable for a ratio. It is not acceptable for a timestamp.
The decision rule is to compare the error against the smallest difference your analysis needs to see. If two values that differ by 1 must stay distinct, float32 fails above 16.7 million. If you only report averages to two decimals, float32 is usually fine.
Side effects of using float32
Smaller floats change behavior in several places beyond storage.
Accumulated error in aggregations
Summing or averaging many float32 values adds rounding error. NumPy reduces the error with pairwise summation, but the result is still float32 and carries about seven digits. For financial totals or long running sums, convert before aggregating:
total = df["price"].astype("float64").sum()This creates a temporary 8-byte copy of that one column. It costs memory briefly, but it keeps the accumulation in higher precision.
Mixed-dtype arithmetic upcasts
An operation between a float32 column and a float64 column returns float64. If you downcast only some columns, derived columns may silently grow back to 8 bytes. Check df.dtypes after feature engineering, not only after loading.
Equality, joins, and keys
A float32 value and its float64 original are different numbers, as the 0.1 example showed. Comparing a downcast column against a float64 constant, or merging a float32 key against a float64 key, can produce no matches. Do not use floats as join keys. If you must, give both sides the same dtype first.
Overflow in float16
float16 tops out at 65,504. Larger values become inf:
import numpy as np
big = np.array([70_000.0, 100.0])
print(big.astype(np.float16)) # [inf 100.]NumPy may emit a RuntimeWarning for the overflow. An inf that appears after a cast is easy to miss, which is why the report helper above checks for it. Many pandas and NumPy operations also have slow or missing code paths for float16, because most hardware has no native 16-bit arithmetic. Prefer float32 unless you are storing data for a model that expects 16-bit input.
When to downcast and when to stay with float64
| Situation | Recommendation |
|---|---|
| Measurements with noise larger than 1e-6 relative (sensor readings, survey scores) | `float32` is usually safe |
| Model features and probabilities in [0, 1] | `float32` is safe, and many ML libraries use it already |
| Money, accounting totals | Keep `float64`, or use integers of cents or `Decimal` |
| Epoch timestamps, IDs stored as floats | Do not use `float32`. Use `int64` or a datetime dtype |
| Values above about 16 million where unit differences matter | Keep `float64` |
| Columns used as join keys or compared for exact equality | Keep one consistent dtype, preferably not float |
Common mistakes
- Trusting the tolerance in
to_numeric. The function decides the cast is acceptable by its own rule, not yours. Runfloat32_reporton columns where precision matters. - Checking only the relative error. A relative error of 1e-7 on a value of 1.7e9 is an absolute error of about 100.
- Casting before cleaning. Strings such as
"N/A"make the columnobject. Fix those first, for example withpd.to_numeric(s, errors="coerce"), then downcast. - Forgetting that new columns default to float64. Results of calculations come back as
float64unless the inputs were allfloat32. Re-apply the cast at the end of a pipeline if memory is tight. - Assuming the saving is large for small tables. Halving a 10,000-row column saves 40 KB. Float downcasting matters when you have many rows or many float columns.
Exercise
A column holds distances in meters, with values between 0 and 40,000,000 (40 million) and a required resolution of 1 meter. Is float32 safe for it? What would you use instead if you also need to keep memory low?
Show answer
No. Above 16,777,216 (2**24), float32 cannot represent every integer, so values near 40 million are spaced 4 meters apart and 1-meter differences are lost. Because the data needs whole-meter resolution, store it as an integer, for example int32 (range about plus or minus 2.1 billion), which uses the same 4 bytes and keeps every value exact. If the column has missing values, use the nullable Int32 dtype.
Exercise
You downcast a price column from float64 to float32, then compute df["price"].sum() on 5 million rows and compare it with the old total. The totals differ in the last digits. What are two reasonable ways to handle this, and when would you choose each?
Show answer
One option is to cast to float64 only for the aggregation, with df["price"].astype("float64").sum(). This costs a temporary copy of that column but keeps full precision for sums. The other is to leave the column as float64 from the start, which is the better choice for money or any total that must reconcile exactly. For prices, storing integer cents in an int64 (or smaller integer) column avoids the rounding issue entirely.