Sub topic 8
Choosing dtypes and measuring memory
This chapter assumes you can run pandas code, read a DataFrame summary, and know that NumPy arrays hold values of a single type. The previous chapters covered timing and vectorizing. Here the question is how much memory each column uses and whether a smaller type can make the same data cheaper to store and faster to process.
Why dtypes affect speed and memory
A dtype is the data type of a column. It decides how many bytes each value takes and which compiled routines pandas can use on it.
Pandas gives you defaults, and the defaults are generous:
- Integers become
int64, 8 bytes each, even if every value is between 1 and 9. - Floats become
float64, 8 bytes each. - Text becomes
object(or a string dtype in newer pandas versions). Withobject, each cell is a pointer to a separate Python string, so the real cost is far above 8 bytes per row.
Large frames can exceed RAM, which causes swapping or crashes. Even when they fit, more bytes means more memory traffic, and memory traffic often limits vectorized code. Smaller dtypes can also speed up groupby, comparisons, and merges.
Measuring memory correctly
Pandas offers three ways to look at memory use. They do not always agree.
| Tool | What it reports | Catch |
|---|---|---|
| `df.memory_usage()` | Bytes per column, plus the index | For `object` columns it counts only the pointers |
| `df.memory_usage(deep=True)` | Also counts the Python objects behind `object` columns | Slower on large frames, but the number to trust |
| `df.info(memory_usage="deep")` | Dtypes, null counts, and a total | A summary only. Use `memory_usage` for per-column numbers |
The shallow figure for a string column can be off by a large factor. Always pass deep=True when you compare before and after.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 500_000
orders = pd.DataFrame({
"order_id": np.arange(n),
"region": rng.choice(["N", "S", "E", "W"], size=n),
"qty": rng.integers(1, 10, n),
"amount": rng.random(n) * 100,
})
print(orders.dtypes)
print(orders.memory_usage(deep=True))
print(f"total: {orders.memory_usage(deep=True).sum() / 1e6:.1f} MB")Expect region to dominate. The exact numbers depend on your pandas version, because pandas 3 uses a dedicated string dtype by default, and that changes how text columns are stored. The method is the same either way: measure, change, measure again.
Category dtype for repeated text
A category column stores each distinct value once, in a list of categories. Each row holds a small integer code that points into that list. If a column has few distinct values compared with its row count, this removes most of the memory.
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)With four distinct values, pandas stores the codes as int8. That is about 1 byte per row, so the column shrinks from tens of megabytes to roughly half a megabyte. You can inspect the structure:
print(cities["city"].cat.categories)
print(cities["city"].cat.codes.dtype)Category columns also speed up groupby and equality comparisons, because pandas can work on the integer codes instead of comparing strings.
When category is the wrong choice
Category helps when values repeat. It can hurt when they do not. If almost every value is unique, pandas stores the codes and the full list of distinct values, which is more than the plain column.
import numpy as np
import pandas as pd
ids = pd.Series(np.arange(200_000)).astype(str)
as_object = ids.memory_usage(deep=True)
as_category = ids.astype("category").memory_usage(deep=True)
print(as_object, as_category)Use a rough rule: convert a column when its distinct values number well under half of its rows, and preferably far fewer. Check with df["col"].nunique() before converting.
Other behaviors to know:
- Assigning a value that is not among the categories raises an error or produces missing values, depending on the operation. Add it first with
cat.add_categories. - In older pandas versions,
groupbyon a category column returns a row for every category, including unused ones. Passobserved=Trueif you want only the combinations that occur. - Arithmetic on a category column does not work. Convert back with
astypeif you need to compute on it. - Category helps most on columns you group, filter, or join by. It helps little on a column you only display.
Downcasting numbers
Downcasting means storing numbers in a smaller type that still holds every value. pd.to_numeric with downcast picks the smallest type for you:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 500_000
orders = pd.DataFrame({
"order_id": np.arange(n),
"region": rng.choice(["N", "S", "E", "W"], size=n),
"qty": rng.integers(1, 10, n),
"amount": rng.random(n) * 100,
})
before = orders.memory_usage(deep=True).sum()
orders["region"] = orders["region"].astype("category")
orders["order_id"] = pd.to_numeric(orders["order_id"], downcast="unsigned")
orders["qty"] = pd.to_numeric(orders["qty"], downcast="unsigned")
orders["amount"] = orders["amount"].astype("float32")
after = orders.memory_usage(deep=True).sum()
print(orders.dtypes)
print(f"{before / 1e6:.1f} MB -> {after / 1e6:.1f} MB")Here qty becomes uint8 (range 0 to 255) and order_id becomes uint32. The downcast="unsigned" option only picks unsigned types, so use it when values are never negative. Use downcast="integer" when they might be.
The ranges of the common numeric types:
| dtype | Bytes | Range or precision |
|---|---|---|
| `int8` / `uint8` | 1 | -128 to 127 / 0 to 255 |
| `int16` / `uint16` | 2 | -32,768 to 32,767 / 0 to 65,535 |
| `int32` / `uint32` | 4 | about ±2.1 billion / 0 to about 4.3 billion |
| `float32` | 4 | about 7 significant digits |
| `float64` | 8 | about 15 to 16 significant digits |
Risks of small types
Small types save memory but cost safety. Two problems come up often.
Integer overflow is silent. When arithmetic exceeds the range, the value wraps around and no error appears:
import pandas as pd
a = pd.Series([200, 100], dtype="uint8")
b = pd.Series([100, 100], dtype="uint8")
print(a + b)The first result is 44, not 300. If a column will be multiplied or summed in place, keep it in a type that holds the result, or cast to a wider type before computing, for example df["qty"].astype("int64") * 1000.
Precision loss affects float32. It keeps about seven significant digits, so it is wrong for money totals, long running sums, or any value that must match another system exactly. It is fine for measurements where seven digits are enough.
Missing values and nullable dtypes
A plain int column cannot hold a missing value. If a column has NaN, pandas turns it into float64. That can double its size and turns whole numbers into floats. Pandas has nullable integer dtypes, written with a capital letter, that avoid this:
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int8")
print(s.dtype)
print(s.memory_usage(deep=True))Int8 stores a small integer plus a separate mask that records which entries are missing. It costs a little more than int8, but less than float64, and it keeps integers as integers. The same pattern exists for Int16, Int32, Int64, Float32, Float64, boolean, and string.
Choosing dtypes at load time
Converting after loading means you first pay for the big version. A better plan is to give the dtypes when you read the file, so the large version never exists. The I/O chapter covers this in depth. This is the pattern:
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)Formats such as Parquet store dtypes in the file, so a category column stays a category column when you read it back. That makes the cost of conversion a one-time cost.
A repeatable workflow
In practice:
- Measure the whole frame with
memory_usage(deep=True)and find the two or three largest columns. Optimizing a column that uses 2 percent of the memory is not worth the risk. - Check
nunique()for text columns andmin()andmax()for integer columns. - Convert, then measure again.
- Run the pipeline and compare outputs with the original.
- Move the conversions into the loading step so they happen once.
Common mistakes
- Reading
memory_usage()withoutdeep=Trueand concluding that text columns are cheap. - Converting every text column to
category, including near-unique ones such as IDs or free-text comments. - Downcasting a column and then computing on it in place, which overflows silently.
- Using
float32for money or for columns that are summed millions of times. - Converting dtypes in the middle of a pipeline, over and over, instead of once when loading.
- Forgetting that a small gain on a small frame is not worth the added complexity. Dtype tuning pays off when the frame is large or memory is limited.
Exercise
A DataFrame has 1,000,000 rows and a column user_id with 950,000 distinct string values, and a column plan with 3 distinct string values. Which column should you convert to category, which should you leave as strings, and what call confirms the saving?
Show answer
Convert plan, because only 3 values repeat across a million rows, so each row becomes a 1-byte code. Leave user_id as strings. Almost every value is unique, so a category would store a code for every row plus nearly the full list of values, which saves little or costs more. Confirm with df["plan"].memory_usage(deep=True) before and after astype("category"). The deep=True argument is needed so the Python string objects in the original column are counted.
Exercise
You downcast qty to uint8 and later compute df["qty"] * 30. For a row with qty = 10, what goes wrong and how do you prevent it?
Show answer
The result is 300, which does not fit in uint8 (maximum 255), so it wraps around to 44 with no error. Prevent it by casting before the arithmetic, for example df["qty"].astype("int64") * 30 or df["qty"].astype("uint16") * 30, or by keeping the column in a wider type if it is used in calculations.