Sub topic 8
Choosing dtypes and measuring memory
This chapter assumes you know basic pandas (selecting columns, groupby, merge) and have used cProfile or perf_counter to find a slow or memory-heavy step. Here you will learn how a column's dtype affects memory and speed, and how to measure it.
Why dtypes matter
A dtype is the data type pandas uses to store a column. The default choices are safe but not always compact.
- Integers default to
int64, and floats tofloat64. Each value takes 8 bytes. - Strings use the
objectdtype. Each value is a separate Python string object, and the column stores a pointer to it.
Smaller or smarter dtypes use less memory. Less memory also means less data to move, so many operations run faster. Memory also decides whether a dataset fits in RAM at all.
Measuring memory correctly
Use memory_usage(deep=True). Without deep=True, pandas counts only the pointers in an object column. It does not count the strings they point to, so the number is far too small.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
cities = pd.DataFrame({
"city": rng.choice(["Oslo", "Lima", "Pune", "Cairo"], size=500_000),
})
before = cities["city"].memory_usage(deep=True)
cities["city"] = cities["city"].astype("category")
after = cities["city"].memory_usage(deep=True)
print(before, after)The column has only four distinct values repeated 500,000 times. As object, it holds many string references. As category, pandas stores each distinct string once, plus a small integer code per row. The second number is much smaller.
For a whole frame, df.memory_usage(deep=True).sum() gives the total in bytes. df.info(memory_usage="deep") prints the same figure per column.
The category dtype
category works best when a column has few distinct values compared to its row count. Typical examples are region, status, and country code.
It also speeds up groupby and comparisons, because pandas works on integer codes instead of strings.
A rule of thumb: try category when distinct values are well under half the rows. Always measure, because a column of mostly unique strings can get larger as a category.
Downcasting numbers
If values fit in a smaller type, you can store them in one. Check the range first, because values outside the range overflow.
| dtype | Bytes per value | Range |
|---|---|---|
| `int8` | 1 | -128 to 127 |
| `int16` | 2 | -32,768 to 32,767 |
| `int32` | 4 | about ±2.1 billion |
| `float32` | 4 | about 7 significant digits |
| `float64` | 8 | about 15 significant digits |
pd.to_numeric can pick the smallest safe integer type for you.
import pandas as pd
s = pd.Series([1, 5, 9, 3, 7])
small = pd.to_numeric(s, downcast="integer")
print(s.dtype, "->", small.dtype)
print(s.memory_usage(), small.memory_usage())Choose dtypes when loading
The cheapest time to set dtypes is at load time, so the large default version never exists in memory. Chapter content on usecols and Parquet covers this in more detail. The core pattern is:
import pandas as pd
df = pd.read_csv(
"orders.csv",
dtype={"region": "category", "amount": "float32"},
)Common errors
- Measuring without
deep=True. Theobjectcolumn looks small, so the real problem stays hidden. - Converting high-cardinality strings to
category. If most values are unique, the category table is as big as the original data. Memory may rise. - Downcasting without checking the range. Casting with
astype("int8")can wrap large values around silently. Preferpd.to_numeric(..., downcast=...), which picks a type that fits. - Forgetting to verify. After changing dtypes, confirm the results match. A later chapter covers this with
assert_series_equal.
Summary of the workflow
- Measure with
memory_usage(deep=True). - Convert repetitive strings to
category. - Downcast numbers whose range allows it.
- Set dtypes at load time.
- Re-measure and compare results.
Exercise
A column status has 2 million rows and only 5 distinct values, stored as object. You call df["status"].memory_usage() and get a small number. Why is it misleading, and what should you call instead?
Show answer
Without deep=True, pandas counts only the pointers in an object column, not the string objects they point to. Call df["status"].memory_usage(deep=True). Then convert the column with astype("category") and measure again. Because there are only 5 distinct values, the category version should be much smaller.
Exercise
A colleague runs df["user_id"].astype("category") on a column where almost every value is unique, and memory use goes up. Why?
Show answer
A category stores every distinct value once, plus an integer code per row. When nearly all values are unique, the table of distinct values is about as large as the original column, and the codes are extra. Category only saves memory when distinct values are few compared to the row count.