Sub topic 12
Dtypes and memory considerations
This chapter assumes you can build a DataFrame, read df.dtypes, and have seen column arithmetic and groupby in the earlier chapters.
Why dtype decides whether code is vectorised
A vectorised operation is fast because pandas hands a typed block of memory, such as 64-bit floats, to compiled code. That only works when every value has the same fixed-size type. A column of dtype object holds pointers to Python objects, so operations on it fall back to Python-level work per value. String columns are the usual case. In pandas 3 the default string dtype is more efficient than object, but older versions still use object.
Check dtypes before you optimise anything:
import numpy as np
import pandas as pd
n = 1_000_000
rng = np.random.default_rng(0)
df = pd.DataFrame({
"store": rng.choice(["north", "south", "east", "west"], size=n),
"qty": rng.integers(1, 20, size=n),
"price": rng.uniform(1, 100, size=n),
})
print(df.dtypes)
print(df.memory_usage(deep=True))deep=True matters. Without it, pandas counts only the pointers in an object column and ignores the strings they point to, so the number is too small.
Shrinking columns
Integers default to int64 and floats to float64, which is more range than most columns need. Repeated strings are better stored as category, which keeps each distinct value once and stores small integer codes for the rows.
small = df.astype({"store": "category", "qty": "int8", "price": "float32"})
before = df.memory_usage(deep=True).sum()
after = small.memory_usage(deep=True).sum()
print(f"{after / before:.0%} of the original size")Smaller columns use less memory and move through the CPU cache faster. groupby on a category column is also cheaper, because it groups on integer codes instead of comparing strings.
| Column contents | Typical choice | Watch for |
|---|---|---|
| Small whole numbers | `int8`, `int16`, `int32` | Overflow |
| Decimals where 7 digits are enough | `float32` | Rounding in long sums |
| Few distinct repeated strings | `category` | Many distinct values gain nothing |
| Whole numbers with gaps | `Int64` (nullable) | Slightly slower than `int64` |
Failure modes
Small integer types wrap around silently when a result no longer fits:
s = pd.Series([100], dtype="int8")
print(s * 2) # 200 does not fit in int8, so the result is -56Missing values change dtypes. A column of integers containing None becomes float64, because plain NumPy integers cannot represent a missing value. If you need to keep whole numbers, use the nullable type:
print(pd.Series([1, 2, None]).dtype) # float64
print(pd.Series([1, 2, None], dtype="Int64").dtype) # Int64Mixed types are the other trap. A column that mixes numbers and strings becomes object, and every vectorised method on it slows down or fails. Convert with pd.to_numeric(col, errors="coerce") early, then inspect the resulting NaN values.
Temporary arrays
Each step of a vectorised expression allocates a new array. In df["a"] * df["b"] + df["c"], the product is built as a full-size temporary before the addition runs. On a large frame, a long chain can briefly hold several extra copies of a column. Two practical responses:
- Drop columns you no longer need and downcast before the heavy calculations.
- Use
df.eval("a * b + c")for long arithmetic expressions. It can reduce temporaries, but it helps mainly on very large frames.
Exercise
A column units is stored as int8. You run df["units"] * 50 and some results are negative, although all inputs are positive. What happened, and how do you fix it?
Show answer
The products exceed 127, the largest int8 value, so they wrapped around. Convert the column to a wider type before multiplying, for example df["units"].astype("int32") * 50.