Sub topic 12
Dtypes and memory considerations
The earlier chapters rewrote loops as column operations. This chapter covers how a column's dtype (its data type) decides whether those operations run fast, and how much memory they use. It assumes you have read the chapters on column arithmetic and groupby, can create a DataFrame, and know that NumPy arrays hold values of one fixed type.
Why dtype decides whether code is vectorised
A vectorised operation is fast because the loop runs in compiled code over a contiguous block of identical values. That only works when the column's dtype lets pandas hand the data to NumPy as a typed array.
- A
float64orint64column is a block of 8-byte numbers. Multiplying two such columns is one compiled loop. - An
objectcolumn is a block of pointers to separate Python objects. Each element can be a different type, so pandas has to look at every element in Python. Operations on it are often only a hidden loop.
You can write a perfectly vectorised-looking expression and still get loop speed if the columns are object. The usual cause is numbers that were read in as strings.
import numpy as np
import pandas as pd
n = 1_000_000
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.uniform(1, 100, n).round(2),
"qty": rng.integers(1, 10, n),
"store": rng.choice(["north", "south", "east", "west"], n),
})
print(df.dtypes)
print(df.memory_usage(deep=True))
print("total MB:", df.memory_usage(deep=True).sum() / 1e6)price is float64 and qty is int64, so each takes 8 MB for one million rows. store is object (or str in pandas 3). With deep=True, pandas counts the text of each string as well as the pointer. The store column typically costs several times more than either numeric column, even though it holds only four distinct values.
Without deep=True, memory_usage counts only the 8-byte pointers for an object column. It then underreports the real cost, so always pass deep=True for text columns.
What each dtype costs
| dtype | Bytes per value | Notes |
|---|---|---|
| `int8` | 1 | Range -128 to 127 |
| `int16` | 2 | Range -32,768 to 32,767 |
| `int32` | 4 | About ±2.1 billion |
| `int64` | 8 | About ±9.2 × 10^18. The default integer type |
| `float32` | 4 | About 7 significant digits |
| `float64` | 8 | About 15 to 16 significant digits. The default float type |
| `bool` | 1 | Result of comparisons, used by masks |
| `category` | 1 to 4 per row | Integer codes, plus one copy of each distinct value |
| `object` | 8 plus the object | A pointer to a separate Python object per value |
Shrinking a dtype saves memory in proportion to the byte count. It can also make operations faster, because more values fit in the CPU cache.
Converting columns safely
Use astype when you know the target type. Use pd.to_numeric when the input might be dirty.
import pandas as pd
raw = pd.Series(["10", "20", "x", None])
# astype would raise on "x". to_numeric can turn bad values into NaN.
clean = pd.to_numeric(raw, errors="coerce")
print(clean)
print(clean.dtype) # float64errors="coerce" hides bad data, so count the values it created before moving on:
bad = clean.isna() & raw.notna()
print("unparseable values:", bad.sum())pd.to_numeric also accepts downcast, which picks the smallest dtype that holds every value:
import numpy as np
import pandas as pd
qty = pd.Series(np.random.default_rng(1).integers(1, 10, 1_000_000))
small = pd.to_numeric(qty, downcast="unsigned")
print(qty.dtype, qty.memory_usage(index=False) / 1e6) # int64, 8.0 MB
print(small.dtype, small.memory_usage(index=False) / 1e6) # uint8, 1.0 MBInteger overflow is silent
NumPy integer arithmetic wraps around when a result does not fit the dtype. pandas does not raise an error.
import pandas as pd
small = pd.Series([100, 100], dtype="int8")
print(small * 2) # -56, -56 with dtype int8
print(small.astype("int64") * 2) # 200, 200This is the main risk of downcasting. A column of quantities that fits int8 today can overflow when you compute qty * price_in_cents or a running total with cumsum. Downcast the columns you store. Before you do arithmetic on them, convert up to the type the result needs.
Missing values change the dtype
NumPy integers cannot hold NaN. One missing value turns an integer column into float64.
import pandas as pd
a = pd.Series([1, 2, None])
b = pd.Series([1, 2, None], dtype="Int64") # capital I: nullable integer
print(a.dtype) # float64
print(b.dtype) # Int64
print(b.isna().tolist()) # [False, False, True]The float conversion matters for two reasons. IDs above 2^53 lose precision as float64. Equality checks and merges can also behave differently than they did before the column picked up a missing value. The nullable dtypes (Int64, Float64, boolean, string) keep the integer type and mark missing values with pd.NA. They are generally slower than plain NumPy dtypes for some operations, so use them where you need the missing-value semantics and not by default.
Category dtype for repeated labels
A column with few distinct values, such as store names, status codes or country names, suits category. pandas stores each distinct value once and keeps a small integer code per row.
import numpy as np
import pandas as pd
n = 1_000_000
rng = np.random.default_rng(0)
store = pd.Series(rng.choice(["north", "south", "east", "west"], n))
as_category = store.astype("category")
print("object :", store.memory_usage(deep=True, index=False) / 1e6, "MB")
print("category:", as_category.memory_usage(deep=True, index=False) / 1e6, "MB")
print(as_category.cat.codes.dtype) # int8The category version uses one byte per row plus a tiny lookup table. Grouping, comparing and mapping on it also tend to be faster, because pandas can work on the integer codes instead of comparing strings.
Category columns have three behaviours to know about:
- Assigning a value that is not among the categories fails or produces
NaN, depending on the operation. Add new labels first with.cat.add_categories. groupbyon a categorical key includes unused categories in its result by default. Passobserved=Trueto get only the groups that appear in the data, and to avoid a pandas deprecation warning.- Category pays off only when the number of distinct values is small compared to the number of rows. For a column of mostly unique values, such as emails, it uses more memory than
object.
import pandas as pd
sales = pd.DataFrame({
"store": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"]),
"amount": [10, 30, 5],
})
print(sales.groupby("store", observed=True)["amount"].sum())Temporaries and peak memory
Each step of a column expression creates a new array. The expression below allocates several one-million-row temporaries before the final assignment:
import numpy as np
import pandas as pd
n = 1_000_000
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.uniform(1, 100, n),
"qty": rng.integers(1, 10, n),
})
df["total"] = df["price"] * df["qty"] * 1.2 + 5For a million rows this is not a problem. For hundreds of millions it can exhaust memory even if the final column fits. Some ways to lower the peak:
- Drop columns you no longer need with
del df["col"]before building large new ones. - Break a long expression into steps so intermediate results can be freed, then delete them.
- Read only the columns you use and set dtypes when loading, for example
pd.read_csv(path, usecols=[...], dtype={...}). - Process the data in chunks when it exceeds memory.
read_csv(..., chunksize=...)yields DataFrames you can reduce one at a time.
Boolean masks are cheap, at one byte per row. They can still add up if you keep many of them alive, so name a mask only if you reuse it.
Choosing a dtype
The diagram summarises the decisions in this chapter.
Common errors
- Vectorising an
objectcolumn and expecting speed. Checkdf.dtypesfirst. Numbers read as text are the usual cause. - Trusting
memory_usage()withoutdeep=True. The shallow figure ignores string contents. - Downcasting and then doing arithmetic. Overflow wraps silently. Convert up before sums, products and cumulative operations.
- Using
float32for money or large totals. Seven digits of precision is not enough, and rounding errors accumulate in sums. - Converting a mostly unique column to
category. It can raise memory use. - Comparing a result with a loop version without matching dtypes.
Series.equalsreturnsFalseif one result isint64and the other isfloat64. When you verify a rewrite, as the earlier chapter on measuring did, checkdtypeas well as values, or usepd.testing.assert_series_equalwithcheck_dtype=Falseif only the values matter.
Exercise
A column qty is stored as int8 and holds values up to 120. You compute df["qty"] * 3 and get negative numbers in some rows. Explain why, and show one way to fix it.
Show answer
int8 holds values from -128 to 127. A result such as 120 3 = 360 does not fit, so NumPy wraps it around without raising an error. Convert to a wider type before the arithmetic: `df["qty"].astype("int64") 3. You can keep qty stored as int8` and widen it only for calculations.
Exercise
A DataFrame has 2 million rows and a country column with 40 distinct values stored as object. Write the code to measure its memory before and after converting to category, and say what you expect to see.
Show answer
Code: before = df["country"].memory_usage(deep=True, index=False), then df["country"] = df["country"].astype("category"), then after = df["country"].memory_usage(deep=True, index=False). With 40 distinct values the codes fit in int8, so after is about 2 MB plus a small lookup table. before is many times larger, because each row holds a pointer and a Python string.