Sub topic 9
Downcasting integers and floats
This chapter assumes you know that each column has one dtype, that int64 and float64 are the defaults, and that memory_usage() reports bytes per column. Downcasting replaces a wide numeric dtype with a narrower one that still holds every value in the column.
Why default dtypes waste memory
pandas picks int64 for integers and float64 for floats. Each value takes 8 bytes, even if the column only holds ages from 0 to 100. NumPy stores values in fixed-width slots, so the width is set by the dtype and not by the data.
| dtype | bytes per value | range |
|---|---|---|
| int8 | 1 | -128 to 127 |
| uint8 | 1 | 0 to 255 |
| int16 | 2 | -32,768 to 32,767 |
| int32 | 4 | about ±2.1 billion |
| float32 | 4 | about 7 significant digits |
| float64 | 8 | about 15 to 16 significant digits |
A column that fits in uint8 can shrink to one eighth of its size.
Using pd.to_numeric with downcast
pd.to_numeric has a downcast argument. It checks the values and returns the smallest dtype of the requested kind that can hold them.
import pandas as pd
s = pd.Series([1, 2, 3, 200])
small = pd.to_numeric(s, downcast="unsigned")
print(s.dtype, s.memory_usage(index=False))
print(small.dtype, small.memory_usage(index=False))The original is int64 at 32 bytes. The result is uint8 at 4 bytes, because 200 is below 255.
The accepted values are:
"integer"or"signed": the smallest signed integer type."unsigned": the smallest unsigned type. If the column has a negative value, nothing is downcast and the column keeps its dtype."float":float32where possible. It never goes belowfloat32.
Downcasting a whole DataFrame
Select columns by kind, then convert each one.
import pandas as pd
n = 1_000_000
df = pd.DataFrame({
"id": range(n),
"age": [20 + i % 60 for i in range(n)],
"score": [i % 100 / 4 for i in range(n)],
})
before = df.memory_usage(index=False).sum()
for col in df.select_dtypes("integer").columns:
df[col] = pd.to_numeric(df[col], downcast="integer")
for col in df.select_dtypes("float").columns:
df[col] = pd.to_numeric(df[col], downcast="float")
after = df.memory_usage(index=False).sum()
print(df.dtypes)
print(before, after)Here id becomes int32, age becomes int8, and score becomes float32. Total memory falls from 24,000,000 bytes to 9,000,000. The score values are multiples of 0.25, so float32 stores them exactly.
Gotchas
- Precision loss.
float32keeps about 7 significant digits.to_numericaccepts the narrower float when the result is close enough, using a tolerance. The new values can therefore differ slightly from the originals. Do not downcast money, coordinates, or any column where small errors matter. - Overflow in later arithmetic. Small integer types wrap around silently when a result no longer fits. A
uint8column holding 200, plus 100, gives 44, not 300. Downcast only columns you will not do arithmetic on, or cast back up before computing. - Future values. The dtype fits today's data. If new data with larger values is appended later, the range check has to be run again.
- Missing values. A float column with
NaNcannot become an integer type. Convert to a nullable dtype such asInt64first, as covered earlier, if you need integers.
Exercise
A column qty holds the integers 0 to 5000 and is stored as int64. What dtype does pd.to_numeric(df["qty"], downcast="unsigned") return, and why not uint8? How many bytes per value does it save?
Show answer
It returns uint16. The maximum value 5000 is above 255, the uint8 limit, but below 65,535, the uint16 limit. Each value drops from 8 bytes to 2, saving 6 bytes per value.
Exercise
A float64 column price holds 19.99, 4.35, and 120.10. A teammate downcasts it with downcast="float" to save memory. Name one risk, and say what you would do instead if exact cents matter.
Show answer
The column may become float32, which keeps only about 7 significant digits, so values can differ slightly from the originals and errors can build up in sums. If exact cents matter, keep float64, or store prices as integer cents.