Sub topic 3
Downcasting Integers with pd.to_numeric
This chapter assumes you can create and index a DataFrame, you know the difference between int64, float64 and object, and you have used memory_usage(deep=True) from the earlier chapters. It also assumes you know what the fixed-width integer dtypes hold. You will use pd.to_numeric(..., downcast=...) to shrink integer columns and check the result. You will also see the silent failure that fixed-width integers can cause.
Why integers are a good first target
By default pandas stores whole numbers as int64, which uses 8 bytes per value. Most real columns hold far smaller numbers. An age never needs 8 bytes, and neither does a rating from 1 to 5. For a column of 100,000 rows, int64 costs 800,000 bytes. An int8 column holding the same values costs 100,000.
Integer downcasting is lossless when done correctly. Each value keeps its exact value, and only the container shrinks. That makes it the safest memory optimization in this tutorial.
The integer dtypes and their ranges
NumPy provides signed and unsigned integers in four widths. Signed types reserve one bit for the sign. Unsigned types use every bit for magnitude but cannot hold negatives.
| dtype | bytes | minimum | maximum |
|---|---|---|---|
| int8 | 1 | -128 | 127 |
| int16 | 2 | -32,768 | 32,767 |
| int32 | 4 | -2,147,483,648 | 2,147,483,647 |
| int64 | 8 | -9.22e18 | 9.22e18 |
| uint8 | 1 | 0 | 255 |
| uint16 | 2 | 0 | 65,535 |
| uint32 | 4 | 0 | 4,294,967,295 |
| uint64 | 8 | 0 | 1.84e19 |
You do not need to memorize these. np.iinfo reports the limits for any integer dtype:
import numpy as np
for name in ["int8", "int16", "int32", "uint8", "uint16", "uint32"]:
info = np.iinfo(name)
print(f"{name:7} {info.bits // 8} bytes {info.min:>15,} to {info.max:,}")The rule for picking a dtype by hand is to take the column's minimum and maximum, then choose the narrowest dtype whose range contains both. If the minimum is 0 or greater, unsigned types double the positive range at the same width. A column that runs from 0 to 50,000 fits in uint16 but not in int16.
Downcasting with pd.to_numeric
pd.to_numeric converts its input to a numeric dtype. Its downcast argument tells it to then pick the smallest dtype that holds every value. It accepts three useful settings:
"integer"(or the synonym"signed") triesint8,int16,int32, thenint64."unsigned"triesuint8,uint16,uint32, thenuint64."float"triesfloat32. The next chapter covers it.
Here is a worked example with three integer columns whose ranges differ:
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),
"delta": rng.integers(-500, 500, n),
})
before = df.memory_usage(deep=True)
print(df.dtypes)
df["user_id"] = pd.to_numeric(df["user_id"], downcast="unsigned")
df["age"] = pd.to_numeric(df["age"], downcast="integer")
df["delta"] = pd.to_numeric(df["delta"], downcast="integer")
after = df.memory_usage(deep=True)
print(df.dtypes)
print(pd.DataFrame({"before": before, "after": after}))The results follow from the ranges:
user_idruns from 0 to 49,999. It is non-negative and below 65,535, so it becomesuint16at 2 bytes per value.ageruns from 18 to 89, which fitsint8at 1 byte per value.deltaruns from -500 to 499. It has negatives and exceeds theint8range, so it becomesint16.
Each column drops from 800,000 bytes to 200,000 (user_id), 100,000 (age) and 200,000 (delta). The index is unchanged and is a small fixed cost for a RangeIndex.
Signed versus unsigned
Use "unsigned" only when you know the column never goes negative, such as IDs, counts or ages. If a column contains a negative value, unsigned downcasting does not shrink it, and the column stays at its original dtype. That is safe, but it can look like the call did nothing.
The unsigned choice also affects later arithmetic. Subtracting two unsigned columns can produce a result that wraps around instead of going negative, which the next section shows. When in doubt, prefer "integer". It costs one extra bit of range and avoids that class of surprise.
Gotcha: arithmetic can overflow silently
A downcast column has a fixed-width dtype, and NumPy does not check for overflow in array arithmetic. If a result does not fit, it wraps around with no error or warning:
import pandas as pd
ages = pd.Series([80, 90], dtype="int8")
print(ages * 2)The true results are 160 and 180. Both exceed 127, so they wrap to -96 and -76. The same thing happens when you add or multiply two int8 columns, or subtract unsigned columns:
import pandas as pd
a = pd.Series([3], dtype="uint8")
b = pd.Series([5], dtype="uint8")
print(a - b)This prints 254, not -2.
Reductions such as sum() are safer because NumPy accumulates small integers in a wider type. That is why the problem is easy to miss. Your totals look right while an element-wise calculation in the same program is wrong.
Other edge cases
Values that do not fit
downcast never discards information. If a value does not fit int8, pandas moves up to the next width. A single large outlier therefore sets the dtype for the whole column. One row with the value 3,000,000,000 keeps an otherwise tiny column at int64, because that value fits neither int8, int16 nor int32. Check df[col].describe() when a column refuses to shrink, and look for the outlier. It may be a data error such as a sentinel value like 999999999.
Strings that look like numbers
pd.to_numeric also parses text, so it can fix a column read as object and shrink it in one step:
import pandas as pd
raw = pd.Series(["1", "2", "300"])
numbers = pd.to_numeric(raw, downcast="integer")
print(numbers.dtype)The value 300 is above 127, so the result is int16. If any entry cannot be parsed, to_numeric raises an error by default. With errors="coerce" it turns bad entries into NaN. A column that contains NaN cannot be an integer column in the classic sense, so it stays float64 and integer downcasting does not apply to it.
Missing values
A plain NumPy-backed integer column cannot hold missing values. If your data has gaps, the column is already float64 (or you must use a nullable dtype such as Int64). Decide how to treat the missing values first. You can fill them with a sentinel that fits the range, or keep a nullable integer dtype. Then downcast.
Assigning new values later
A narrow dtype is a commitment about the data's range. If you later assign a value that does not fit, for example df.loc[0, "age"] = 200 into an int8 column, the behavior depends on your pandas version. Some versions upcast the column, some warn, and some will raise an error in the future. Downcasting works best on data that is finished changing, such as data you are about to analyze or save.
Verifying the result
Downcasting is lossless, and you can prove it cheaply. Compare each downcast column against the original before you overwrite it:
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
original = pd.Series(rng.integers(-500, 500, 10_000))
small = pd.to_numeric(original, downcast="integer")
assert (original == small).all()
print(original.dtype, "->", small.dtype)
print(original.memory_usage(index=False), "->", small.memory_usage(index=False))Exact equality is the right test for integers, because there is no rounding. The comparison works even though the dtypes differ, since pandas compares by value. Dtype tests such as small.dtype == "int16" are useful as a second check, but they only tell you that the cast happened. They do not tell you the values survived.
Quick reference
| Situation | Setting | Typical result |
|---|---|---|
| Column never negative (IDs, counts) | `downcast="unsigned"` | `uint8` to `uint32` |
| Column may be negative | `downcast="integer"` | `int8` to `int32` |
| Column has negatives, `"unsigned"` requested | any | unchanged |
| Column has `NaN` | none applies | stays `float64` |
| One huge outlier | any | wide dtype for the whole column |
Practice
Exercise
A column visits contains the integers 0 through 70,000 and has no missing values. What dtype does pd.to_numeric(df["visits"], downcast="unsigned") return, and why does downcast="integer" return a different dtype?
Show answer
With "unsigned" the result is uint32, because 70,000 exceeds the uint16 maximum of 65,535 but fits within uint32. With "integer" the result is also int32, because 70,000 exceeds the int16 maximum of 32,767. Both are 4 bytes per value. The two modes would differ for a column that stops at 60,000, which becomes uint16 (2 bytes) when unsigned but int32 (4 bytes) when signed.
Exercise
You downcast price_cents to int16, and later compute df["price_cents"] * 100 to get a value in a smaller currency unit. The results look wrong for some rows. What happened, and how do you fix it?
Show answer
The product no longer fits in int16, whose maximum is 32,767, so it wrapped around silently. A price of 400 gives 40,000, which wraps to a negative number. Fix it by casting before the calculation, for example df["price_cents"].astype("int64") * 100. Alternatively, keep the wide dtype until the calculation is finished and downcast afterwards.