Sub topic 17
Choosing dtypes for memory and speed
This chapter assumes you can build a DataFrame, read its dtypes, and run groupby. It shows how dtype choice changes memory use and speed, and where the savings stop.
Why dtype affects cost
Each column stores its values in one dtype. Text columns use the object dtype by default. An object column holds a pointer to a separate Python string for every row, so repeated labels such as "EU" take space again and again. Numeric columns default to 64-bit types, even when the values are small.
Measuring memory
Use memory_usage(deep=True). Without deep=True, pandas counts only the pointers in an object column and not the strings behind them.
import pandas as pd
df = pd.DataFrame({
"region": ["EU", "SA", "AS", "EU"] * 25_000,
"pop_m": [0.7, 10.7, 3.1, 2.8] * 25_000,
})
before = df.memory_usage(deep=True)
print(before)
df["region"] = df["region"].astype("category")
df["pop_m"] = df["pop_m"].astype("float32")
after = df.memory_usage(deep=True)
print(after)
print(f"total: {before.sum()} -> {after.sum()} bytes")The category dtype
A category column stores each distinct value once. Each row holds a small integer code that points to that value. The savings are large when a column has few distinct values compared to its row count. A column of unique IDs gains nothing and can get bigger.
Categories can also speed up groupby, because pandas groups by the integer codes instead of comparing strings.
Downcasting numbers
Smaller numeric types use less memory. float32 uses half the bytes of float64. Integers come in int8, int16, int32, and int64. Pick the smallest type whose range fits your data. pd.to_numeric can choose for you.
import pandas as pd
ages = pd.Series([21, 35, 48, 62])
small = pd.to_numeric(ages, downcast="integer")
print(ages.dtype, "->", small.dtype) # int64 -> int8Common errors
- Overflow. An
int8holds -128 to 127. Arithmetic that exceeds the range can wrap around silently, so check the range before you downcast. - Lost precision.
float32keeps about 7 significant digits. Avoid it for money or for long running sums. - Categories and new values. Assigning a value that is not among the categories raises an error or gives
NaN, depending on the operation. Add categories first withcat.add_categories. - Premature tuning. Measure first. A small table gains nothing from dtype work.
Quick checklist
- Run
df.info(memory_usage="deep")to find the heavy columns. - Convert low-cardinality text columns to
category. - Downcast numbers whose range is known.
- Measure again and compare.
Exercise
A column has 1,000,000 rows and 900,000 distinct text values. Is converting it to category a good idea? Why?
Show answer
No. Almost every row has its own value, so the categories table is nearly as large as the original data, and the integer codes add more on top. Category helps when distinct values are few compared to the row count.
Exercise
Why can df.memory_usage() understate the size of a text column, and how do you fix it?
Show answer
For object columns it counts only the pointers, not the Python strings they refer to. Call df.memory_usage(deep=True) to include the strings.