Sub topic 13
Downcasting numbers and checking memory use
This chapter assumes you can load a DataFrame, read df.dtypes, and convert columns with pd.to_numeric and astype. Here you will measure how much memory a column uses, then shrink it with downcasting and the category dtype.
Why memory matters
pandas picks wide default types. Integers load as int64 (8 bytes per value) and floats as float64. Text is stored as object, where each value is a separate Python object. On a small table this is harmless. On millions of rows it can exhaust RAM. Smaller dtypes also make some operations faster.
Measuring memory
Series.memory_usage() and DataFrame.memory_usage() report bytes. Pass deep=True for object columns. Without it, pandas counts only the pointers and ignores the strings they point to.
import pandas as pd
s = pd.Series([1, 2, 3, 100])
print(s.dtype, s.memory_usage(index=False, deep=True))
small = pd.to_numeric(s, downcast="integer")
print(small.dtype, small.memory_usage(index=False, deep=True))The first line shows int64 and 32 bytes (4 values × 8 bytes). The second shows int8 and 4 bytes. index=False leaves out the index, so you see only the column data.
Downcasting with pd.to_numeric
The downcast argument of pd.to_numeric picks the smallest type that can hold every value in the column. It accepts these options:
| Option | Possible result |
|---|---|
| `"integer"` | `int8`, `int16`, `int32`, `int64` |
| `"signed"` | same as `"integer"` |
| `"unsigned"` | `uint8` to `uint64`, only if no value is negative |
| `"float"` | `float32` (the smallest float it uses) |
If the values do not fit a smaller type, pandas keeps the larger one. A column of floats with NaN cannot become a plain integer type, so it stays a float. For integers with missing values, convert to the nullable Int64 first, as covered earlier in this tutorial.
df = pd.DataFrame({
"qty": [3, 5, 7, 250],
"score": [0.5, 1.25, 3.75, 9.0],
})
before = df.memory_usage(index=False).sum()
df["qty"] = pd.to_numeric(df["qty"], downcast="unsigned")
df["score"] = pd.to_numeric(df["score"], downcast="float")
after = df.memory_usage(index=False).sum()
print(df.dtypes)
print(before, "->", after)qty becomes uint8 because its largest value, 250, is below 255. score becomes float32.
Shrinking repeated text with category
A column such as status holds a few distinct labels repeated many times. The category dtype stores each label once and keeps a small integer code per row.
status = pd.Series(["shipped", "pending", "shipped", "returned"] * 25_000)
print(status.memory_usage(index=False, deep=True))
cat = status.astype("category")
print(cat.memory_usage(index=False, deep=True))The category version is far smaller, because the 100,000 rows share three stored strings. The saving shrinks as the number of distinct values approaches the number of rows. A column of unique IDs gains nothing from category.
Common errors
- Forgetting
deep=True. Theobjectcolumn looks much cheaper than it really is. - Downcasting too early. If you later add a large number to a narrow integer column, the result can overflow or be cast back up. Downcast after cleaning, at the end of the pipeline.
- Expecting an integer from a column with
NaN. The result stays a float unless you useInt64. - Using
float32for money or other precise values. It keeps about 7 significant digits. Keepfloat64when precision matters.
Exercise
A column age holds the integers 18, 34, 52 and 91. You run pd.to_numeric(df["age"], downcast="unsigned"). What dtype do you expect, and how many bytes does the column use for 1,000 rows (excluding the index)?
Show answer
The dtype is uint8, because all values are non-negative and below 256. Each value takes 1 byte, so 1,000 rows use 1,000 bytes. The original int64 column would use 8,000 bytes.
Exercise
Why can df.memory_usage() understate the size of a text column, and what argument fixes it?
Show answer
For object columns, pandas counts only the pointers by default, not the Python strings they refer to. Calling df.memory_usage(deep=True) inspects the strings and reports the real size.