Sub topic 9
Downcasting integers and floats
This chapter assumes you can build a DataFrame and read its dtypes. You should also know that a numeric column is stored as a fixed-width NumPy array, and that memory_usage() reports bytes per column. Both ideas come from earlier chapters.
Why downcasting saves memory
A default integer column is int64. Each value takes 8 bytes, even if every value is a small number such as an age. A default float column is float64, also 8 bytes per value. Downcasting means storing the same numbers in a narrower dtype of the same kind: int64 becomes int8, int16 or int32, and float64 becomes float32.
The memory for a numeric column is the number of rows times the item size, so the saving is predictable. Going from int64 to int8 cuts that column to one eighth. Going from float64 to float32 halves it.
The cost is range and precision. A narrower dtype can hold fewer distinct values, and the compiler of your data (pandas) will not warn you if you choose a width that is too small. The rest of the chapter covers how to pick safely.
What each width can hold
| dtype | bytes | smallest value | largest value |
|---|---|---|---|
| int8 | 1 | -128 | 127 |
| uint8 | 1 | 0 | 255 |
| int16 | 2 | -32,768 | 32,767 |
| uint16 | 2 | 0 | 65,535 |
| int32 | 4 | -2,147,483,648 | 2,147,483,647 |
| uint32 | 4 | 0 | 4,294,967,295 |
| int64 | 8 | about -9.2 × 10^18 | about 9.2 × 10^18 |
You can read these limits from NumPy instead of memorizing them:
import numpy as np
for name in ["int8", "uint8", "int16", "int32"]:
info = np.iinfo(name)
print(name, info.min, info.max)
print(np.finfo("float32").eps, np.finfo("float64").eps)np.iinfo describes integer types and np.finfo describes float types. The eps value is the gap between 1.0 and the next representable number, which is a rough measure of precision.
Downcasting with pd.to_numeric
pd.to_numeric(values, downcast=...) picks the smallest dtype that holds every value in the column. It takes one of three downcast options.
| `downcast=` | Result |
|---|---|
| `"integer"` or `"signed"` | Smallest signed integer type that fits the values |
| `"unsigned"` | Smallest unsigned integer type that fits the values |
| `"float"` | `float32` if the values allow it, otherwise unchanged |
Here is the smallest case, with one value that needs more than a signed byte:
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 first line prints int64 32 and the second prints uint8 4. Four values at 8 bytes is 32 bytes, and four values at 1 byte is 4 bytes. The value 200 does not fit in int8, which is why the unsigned option matters here. With downcast="integer" the same column becomes int16.
to_numeric also converts text to numbers, so it works as a parse and a downcast in one step:
import pandas as pd
raw = pd.Series(["1", "2", "300"])
parsed = pd.to_numeric(raw, downcast="integer")
print(parsed.dtype)This prints int16, because 300 is too large for int8.
Behavior to know
- The result depends on the data in the column right now. If one value is large, the whole column stays wide.
downcast="unsigned"leaves a column alone if it contains a negative number. It does not raise an error.to_numericreturns a new Series. It never changes the original column in place.- Float columns that contain
NaNcannot become NumPy integer columns. Missing values are covered in the next section.
Downcasting a whole DataFrame
to_numeric works on one column at a time. A short helper applies it to every integer and float column and leaves other columns untouched:
import numpy as np
import pandas as pd
def shrink(df):
out = df.copy()
for col in out.select_dtypes(include="integer").columns:
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="float").columns:
out[col] = pd.to_numeric(out[col], downcast="float")
return out
n = 1_000_000
rng = np.random.default_rng(0)
df = pd.DataFrame({
"user_id": np.arange(n),
"age": rng.integers(0, 100, size=n),
"balance": rng.integers(0, 4000, size=n) / 4,
})
small = shrink(df)
print(small.dtypes)
print(df.memory_usage(index=False).sum())
print(small.memory_usage(index=False).sum())The three columns shrink as follows.
user_idholds 0 to 999,999. That exceedsint16, so it becomesint32(4 MB instead of 8 MB).ageholds 0 to 99 and becomesint8(1 MB).balanceholds multiples of 0.25, whichfloat32stores exactly, so it becomesfloat32(4 MB).
The totals are 24,000,000 bytes before and 9,000,000 bytes after. The balance values were chosen as multiples of 0.25 on purpose, because arbitrary floats behave differently, as the next sections explain.
The select_dtypes(include="integer") call matches signed and unsigned NumPy integers and also the nullable Int8 to Int64 family. For nullable columns, see the section on missing values below.
Floats lose precision, not only range
An integer either fits in its dtype or it does not. A float always fits, but it may be rounded. A float32 has about 7 significant decimal digits, while a float64 has about 15 or 16.
import numpy as np
print(float(np.float32(0.1)))
print(float(np.float32(16_777_217)))The first line prints 0.10000000149011612. The decimal 0.1 has no exact binary form in either width, but float32 is further from it. The second line prints 16777216.0. Above 2^24 = 16,777,216, a float32 cannot represent every integer, so 16,777,217 is rounded to its neighbour.
This is why downcast="float" needs a decision from you:
- For measurements, prices with a few decimals, and ratios, seven digits is often enough.
- For identifiers stored as floats, large counters, or money that you add up many times, it is not. Rounding errors also accumulate when you sum millions of
float32values. to_numericdecides whether to accept the narrower float using a numeric tolerance. Depending on the data and the pandas version, it may skip a column you expected to shrink, or accept a small rounding difference. Do not rely on it as proof that the data is unchanged.
When you have decided that float32 is acceptable, state it explicitly and measure the change:
import numpy as np
import pandas as pd
x = pd.Series(np.random.default_rng(1).random(1_000))
x32 = x.astype("float32")
print(x.dtype, x32.dtype)
print((x - x32.astype("float64")).abs().max())The last line prints the largest rounding error. For values between 0 and 1 it is below about 3 × 10^-8. You can then judge whether that is acceptable for your use.
Gotchas with small integers
Narrow integer types do not warn you when a value goes out of range. Two situations cause silent wrong answers.
Forcing a cast with astype
to_numeric checks the range for you. astype does not always check it:
import numpy as np
a = np.array([1, 200])
print(a.astype(np.int8))This prints [ 1 -56]. The value 200 wraps around in 8 bits. If you pick a dtype by hand, compare against np.iinfo first, or use to_numeric and read the dtype it chose.
Arithmetic stays in the small dtype
When you add or multiply a small-integer column by a number, the result usually keeps the small dtype. It can then overflow:
import pandas as pd
s = pd.Series([200, 100], dtype="uint8")
print((s + 100).tolist())
print((s.astype("int64") + 100).tolist())The first line prints [44, 200], because 200 + 100 = 300 wraps to 44 in a uint8. The second line prints [300, 200]. Aggregations such as sum() normally accumulate in a wider type, but element-wise operations do not.
A practical rule: store narrow dtypes, and widen the column with astype just before arithmetic that can grow the values.
Data grows over time
You choose a dtype from the data you have today. If the same pipeline later receives an age of 150 or a user_id above 2 billion, a hard-coded int8 or int32 will break or wrap. For pipelines that run repeatedly, add a check that the incoming range fits the chosen dtype.
Missing values and nullable integers
A NumPy integer column cannot hold a missing value. If a column has missing entries, pandas stores it as float64 with NaN. Downcasting that float column to float32 saves memory but does not restore the integers.
The nullable integer dtypes keep integers and allow missing values. They come in the same widths: Int8, Int16, Int32 and Int64. Note the capital letter.
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int8")
print(s.dtype)
print(s.memory_usage(index=False))This prints Int8 and then 6. A nullable column stores a data array plus a separate boolean mask that marks which entries are missing. That is 1 byte for each value and 1 byte for each mask entry, so 3 values take 6 bytes. A nullable Int8 still takes less than a plain int64 column (8 bytes per value) but twice as much as a plain int8.
Choosing a dtype
The diagram summarizes the decision for a numeric column.
Before applying this to a real table, check three more things:
- Measure first. A column that is already
int32orfloat32, or a table dominated byobjectcolumns, gains little from downcasting. Usememory_usage(deep=True)to find the large columns. - Compare results. After shrinking, run
small.equals(df)for exact types, or compare withnp.allclosefor floats, on a sample of your own operations. - Do the cheap work at load time when you can. The
dtype=argument ofread_csvlets you skip the wideint64stage entirely, which a later chapter covers.
Exercises
Exercise
A column has the integer values 0, 5, 130 and 250. What dtype does pd.to_numeric(s, downcast="integer") return, what dtype does downcast="unsigned" return, and why do they differ?
Show answer
"integer" returns int16, because 130 and 250 exceed the int8 maximum of 127. "unsigned" returns uint8, because the values all lie between 0 and 255 and an unsigned byte has that range. Signed types spend half their range on negative numbers, so they cannot store 250 in one byte.
Exercise
You downcast a uint8 column qty holding the values 200 and 100, and then compute qty * 2. What does the column contain afterwards, and how do you avoid the problem?
Show answer
The result stays uint8 and wraps around modulo 256, so 200 2 = 400 becomes 144, and 100 2 = 200 stays 200. To avoid it, convert before the arithmetic with qty.astype("int64") * 2, or keep such columns in a wider dtype.
Exercise
A float column named price has 5 million rows and values like 19.99. You consider downcast="float" to save 20 MB. Give two reasons to check the result before accepting it, and one way to check.
Show answer
First, float32 keeps only about 7 significant digits, so values such as 19.99 are rounded and the rounding can accumulate when you sum millions of rows. Second, to_numeric decides using a tolerance, so it may skip the column or accept a small change you did not intend. To check, compute the maximum absolute difference with (price - price.astype("float32").astype("float64")).abs().max() and compare it with the error your use case can accept.