Sub topic 3
Downcasting integers with pd.to_numeric
This chapter assumes you can build and index DataFrames and know the basic pandas dtypes (int64, float64, object). It also assumes you have seen memory_usage(deep=True), which this chapter uses to measure savings.
Why integers are oversized
pandas stores whole-number columns as int64 by default. Each value takes 8 bytes, even when the column only holds ages between 18 and 89. NumPy offers narrower integer types, and each one covers a fixed range.
| dtype | Bytes | Range |
|---|---|---|
| int8 | 1 | -128 to 127 |
| int16 | 2 | -32,768 to 32,767 |
| int32 | 4 | about ±2.1 billion |
| uint8 | 1 | 0 to 255 |
| uint16 | 2 | 0 to 65,535 |
| uint32 | 4 | 0 to about 4.29 billion |
The "u" types are unsigned. They hold no negative numbers, so they reach twice as high.
Downcasting with pd.to_numeric
pd.to_numeric has a downcast argument. It checks the column's minimum and maximum, then returns the smallest dtype that holds every value. There are two useful modes:
downcast="integer"(or"signed") picks the smallest signed type.downcast="unsigned"picks the smallest unsigned type.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
})
before = df.memory_usage(deep=True)
df["age"] = pd.to_numeric(df["age"], downcast="integer")
df["user_id"] = pd.to_numeric(df["user_id"], downcast="unsigned")
after = df.memory_usage(deep=True)
print(df.dtypes)
print(pd.DataFrame({"before": before, "after": after}))age runs from 18 to 89, so it becomes int8: 100,000 bytes instead of 800,000. user_id runs from 0 to 49,999. That exceeds int16, but it fits uint16, so it takes 200,000 bytes. With downcast="integer", user_id would have become int32 and used twice that.
What to know before you apply it
Unsigned mode ignores negative data. If a column contains a negative value, downcast="unsigned" cannot use an unsigned type. pandas does not raise an error. It leaves the column as it was, so check the dtype afterwards.
The result depends on the current data. The chosen dtype reflects the values present now. If later data holds an age of 200, int8 cannot store it. Downcast with the range you expect in production, not only the range of your sample.
Small types wrap around in arithmetic. NumPy does not warn when a fixed-width integer overflows.
s = pd.Series([100], dtype="int8")
print(s + s) # 200 does not fit in int8, so it wraps to -56Before you do arithmetic on a downcast column, cast it back up with astype("int64"). Operations such as sums and products can easily exceed the narrow range.
Missing values change the dtype. A column of integers with NaN is already float64, so integer downcasting does not apply to it. Fill or drop the missing values first, or use a nullable integer type such as "Int16".
Choosing the dtype yourself
to_numeric is convenient, but you can also read the limits from NumPy and set the dtype directly. This is useful when you know the real-world range in advance.
print(np.iinfo("int8"))
print(np.iinfo("uint16").max)
df["age"] = df["age"].astype("int8")If a value falls outside the target range, astype on a NumPy-backed column may wrap it silently. to_numeric avoids this because it only picks a type after reading the actual data.
Exercise
A column visits holds integers from 0 to 70,000 and has no negative values. Which dtype does pd.to_numeric(df["visits"], downcast="unsigned") return, and why not uint16?
Show answer
It returns uint32. The maximum value, 70,000, is above the uint16 limit of 65,535, so the column needs the next size up. That is 4 bytes per value, still half of int64.
Exercise
You downcast score_diff, which contains negative numbers, with downcast="unsigned". The dtype is still int64 afterwards. What happened, and what should you change?
Show answer
Unsigned types cannot hold negative values, so pandas left the column unchanged without raising an error. Use downcast="integer" to get the smallest signed type.