Sub topic 17
Choosing dtypes for memory and speed
This chapter assumes you can already read df.dtypes, convert with astype, and use groupby. It covers how to measure what a DataFrame costs in memory and how to pick dtypes that make it smaller and faster, without introducing silent bugs.
Why dtype choice changes cost
pandas stores each column as an array of one dtype. A numeric column such as int64 uses 8 bytes per value, stored contiguously. An object column stores 8-byte pointers to separate Python objects, so every string costs the pointer plus the string object itself. Operations on object columns also run Python-level code per element, which is slower than the compiled loops used for numeric arrays.
Three levers matter most:
- Use smaller numeric types when the value range allows it.
- Use
categoryfor columns with few distinct values. - Use nullable dtypes (
Int64,boolean,string) when you need missing values without changing the column's type.
Measuring memory first
Do not guess. memory_usage(deep=True) counts the real size of object contents. Without deep=True, an object column reports only its pointers and looks much smaller than it is.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"region": rng.choice(["EU", "SA", "AS"], size=n),
"count": rng.integers(0, 200, size=n),
"price": rng.random(n) * 100,
})
before = df.memory_usage(deep=True).sum()
df["region"] = df["region"].astype("category")
df["count"] = pd.to_numeric(df["count"], downcast="unsigned")
df["price"] = df["price"].astype("float32")
after = df.memory_usage(deep=True).sum()
print(df.dtypes)
print(f"before: {before:,} bytes, after: {after:,} bytes")
print(f"ratio: {before / after:.1f}x")The exact byte counts depend on your pandas version. On pandas 2.x, region starts as object, which is the expensive case. After conversion, region is stored as int8 codes, count becomes uint8 (its values fit in 0 to 255), and price uses 4 bytes per value instead of 8. The total typically drops to a fraction of the original.
Downcasting numeric columns
pd.to_numeric(..., downcast=...) picks the smallest type that holds every value in the column. Use "integer", "signed", "unsigned", or "float".
astype("int32") and similar calls choose the type yourself. That gives you control, but you must check the range first with s.min() and s.max().
Two failure modes to know:
- Overflow wraps silently in arithmetic. Small integer types do not widen when a result is too large.
float32has about 7 significant decimal digits. It is fine for measurements, but not for money or for values that must round-trip exactly.
import pandas as pd
s = pd.Series([100, 120], dtype="int8")
print((s * 2).tolist()) # [-56, -16]: wrapped, no error
print((s.astype("int64") * 2).tolist()) # [200, 240]If a column will be used in sums, products, or other arithmetic that can grow, either keep it at a wider type or convert to a wider type before computing.
The category dtype
A category column stores each distinct value once, in a categories index, and keeps a small integer code per row. Memory falls from one string per row to one small integer per row, plus the distinct strings once.
It pays off when the number of distinct values is well below the number of rows. For a column where almost every value is unique, such as an ID or a free-text field, category adds overhead and saves nothing.
Speed benefits follow from the same design. groupby on a category groups by integer codes, and value_counts and comparisons can work on the categories instead of every row.
Category gotchas
- Setting a value outside the categories raises an error. Add the category first.
groupbymay include unobserved categories. In pandas 2.x the default isobserved=False, so groups with no rows appear in the result and give a FutureWarning. Passobserved=Trueexplicitly to get only groups that occur. The default is expected to change in later versions, so being explicit keeps your results stable.- Combining tables can undo the saving.
concatof two category columns with different category sets producesobject. Align the categories first, or convert after combining. - Order is not meaningful by default. Sorting uses the order of
categories. If you need a specific order such aslow < medium < high, use an orderedCategoricalDtype.
import pandas as pd
s = pd.Series(["EU", "SA", "EU"], dtype="category")
s = s.cat.add_categories(["AS"])
s.iloc[1] = "AS"
print(s.tolist()) # ['EU', 'AS', 'EU']
print(s.cat.categories.tolist()) # ['EU', 'SA', 'AS']Nullable dtypes
By default, an integer column that gains a missing value becomes float64, because NumPy integers cannot hold NaN. That changes both memory and meaning, since large integers lose exact representation as floats.
The nullable dtypes avoid this. They use pd.NA as the missing marker:
| Dtype | Holds | Replaces |
|---|---|---|
| `Int64`, `Int32`, `UInt8`, ... | Integers plus `pd.NA` | `float64` used only to hold NaN |
| `Float64` | Floats plus `pd.NA` | `float64` |
| `boolean` | True, False, `pd.NA` | `object` holding None |
| `string` | Text plus `pd.NA` | `object` holding strings |
Note the capital letters: Int64 is the nullable type and int64 is the NumPy type. Mixing them up is a common source of confusing dtype output.
Setting dtypes when you load data
Converting after loading means you pay the larger memory cost first. read_csv accepts dtype and usecols, so you can load directly into the cheaper representation and skip columns you do not need.
import io
import pandas as pd
csv = io.StringIO("id,region,qty,note\n1,EU,5,\n2,SA,7,ok\n3,EU,,ok\n")
df = pd.read_csv(
csv,
dtype={"id": "int32", "region": "category", "qty": "Int64", "note": "string"},
)
print(df.dtypes)
print(df["qty"].tolist()) # [5, 7, <NA>]Here qty has a blank value. As Int64 it keeps integer values and shows <NA>, where a plain int64 request would fail on the blank.
Choosing a dtype
Practical guidance
- Measure before and after with
memory_usage(deep=True). Keep a change only if the saving matters for your data size. - Do not shrink dtypes on small data. A few kilobytes saved are not worth the overflow and precision risks.
- Apply conversions near the start of a pipeline, ideally in
read_csv, so later steps work with the compact types. - Time a real operation with
%timeitortime.perf_counter()on your own data. Gains fromcategoryand numeric types are largest for repeatedgroupbyand comparison work.
Exercise
A DataFrame has 2 million rows. Column country has 40 distinct strings, column user_id has 2 million unique strings, and column age has integers from 0 to 110 with no missing values. Which dtype would you choose for each column, and why?
Show answer
Use category for country, because 40 distinct values across 2 million rows means each row stores a one-byte code instead of a string. Keep user_id as string (or object), because nearly every value is unique, so category would store a code per row plus the full list of categories and save nothing. Use uint8 for age, since 0 to 110 fits in 0 to 255. Check age.min() and age.max() first, and widen the type before doing arithmetic that could exceed 255.
Exercise
A column of integers is read from a CSV, and a few rows are blank. pandas loads it as float64. How do you keep it as integers, and what does a missing entry look like afterwards?
Show answer
Load it with dtype="Int64" for that column in read_csv, or convert with astype("Int64") if the floats are whole numbers. The capital-I dtype is nullable, so values stay integers and missing entries appear as <NA> (pd.NA) instead of NaN.