Sub topic 13
Downcasting numbers and checking memory use
This chapter covers the last step of cleaning a column's dtype: making it smaller once it is correct. It assumes you can load a DataFrame, read df.dtypes, and convert columns with astype and pd.to_numeric. It also assumes you know the category dtype from earlier in this tutorial. Memory work comes last because a correct dtype matters more than a small one.
Why memory depends on dtype
Every column is stored as a block of values, and the dtype sets the size of each value. By default pandas picks the widest common types: int64 for whole numbers and float64 for decimals. Each value takes 8 bytes, even when a column only holds ages between 0 and 100.
For a few thousand rows this does not matter. For tens of millions of rows it can decide whether a DataFrame fits in RAM. Text columns are usually the largest cost. An object column stores a pointer per row, and each pointer refers to a separate Python string.
Shrinking dtypes has two steps:
- Measure the current memory use.
- Convert columns to narrower types, but only where the data fits.
Measuring memory use
DataFrame.memory_usage() returns the bytes used by each column. It has two options that change the answer.
deep=Trueinspects the actual Python objects inobjectcolumns. Without it, pandas counts only the 8-byte pointers and badly underestimates text columns.index=Falseleaves out the index, so you see only the columns.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"status": rng.choice(["shipped", "pending", "returned"], size=n),
"qty": rng.integers(1, 100, size=n),
"price": rng.random(n) * 100,
})
before = df.memory_usage(deep=True, index=False)
print(df.dtypes)
print(before)
df.info(memory_usage="deep")qty and price each use 800,000 bytes, which is 100,000 rows times 8 bytes. The status column uses several megabytes, even though it has only three distinct values. df.info(memory_usage="deep") prints the same measurement as a single total at the bottom.
Without deep, df.info() shows a trailing + after the memory figure, as in 3.1+ MB. That sign means the figure is a lower bound, because object columns were not fully measured.
Downcasting with pd.to_numeric
pd.to_numeric has a downcast argument. After parsing, it picks the smallest dtype that can hold every value in the column. It takes three values.
| `downcast` value | Candidate dtypes, smallest first |
|---|---|
| `"integer"` | `int8`, `int16`, `int32`, `int64` |
| `"signed"` | the same as `"integer"` |
| `"unsigned"` | `uint8`, `uint16`, `uint32`, `uint64` |
| `"float"` | `float32`, then `float64` |
Here is a small example:
import pandas as pd
s = pd.Series([1, 2, 3, 100])
print(s.dtype, s.memory_usage(deep=True, index=False))
small = pd.to_numeric(s, downcast="integer")
print(small.dtype, small.memory_usage(deep=True, index=False))The first line prints int64 32: four values of 8 bytes each. The second prints int8 4, because the largest value, 100, fits in a signed 8-bit integer. I passed index=False so the numbers show only the data. By default Series.memory_usage also counts the index.
The ranges of the integer types decide what fits. You can read them from NumPy:
| dtype | Smallest value | Largest value |
|---|---|---|
| `int8` | -128 | 127 |
| `uint8` | 0 | 255 |
| `int16` | -32,768 | 32,767 |
| `uint16` | 0 | 65,535 |
| `int32` | -2,147,483,648 | 2,147,483,647 |
| `uint32` | 0 | 4,294,967,295 |
import numpy as np
print(np.iinfo("int16"))
print(np.finfo("float32"))np.iinfo and np.finfo also report the range and, for floats, the precision of a dtype.
Converting a whole DataFrame
Apply the conversions column by column, then compare the totals. This example reuses df and before from the measuring step.
df["status"] = df["status"].astype("category")
df["qty"] = pd.to_numeric(df["qty"], downcast="unsigned")
df["price"] = df["price"].astype("float32")
after = df.memory_usage(deep=True, index=False)
report = pd.DataFrame({
"dtype": df.dtypes.astype(str),
"before_bytes": before,
"after_bytes": after,
})
print(report)
print(f"total: {before.sum():,} -> {after.sum():,} bytes")Three things happen here:
qtyholds values from 1 to 99, sodowncast="unsigned"picksuint8. That is 100,000 bytes instead of 800,000.pricegoes tofloat32, which halves it to 400,000 bytes.statusbecomescategory. Pandas stores one small integer code per row (int8here, so about 100,000 bytes) plus one copy of each label. This is the biggest saving, from several megabytes to about 100 KB.
Choosing what to convert
Not every column should shrink. The diagram shows one way to decide.
Use category only when the number of unique values is small compared with the number of rows. You can check this with df["status"].nunique() / len(df). A column where almost every value is unique gets no saving from category. It can even use more memory, because pandas stores the labels and also the codes.
Failure modes
Silent overflow with astype
pd.to_numeric(..., downcast=...) checks the range for you. astype does not. If you force a narrow type on values that do not fit, the values wrap around without any error:
import pandas as pd
s = pd.Series([100, 200, 300])
print(s.astype("int8"))The output is 100, -56, 44. The data is corrupted and nothing warns you. When the target type is chosen by hand, check the range first:
import numpy as np
import pandas as pd
s = pd.Series([100, 200, 300])
info = np.iinfo("int8")
fits = s.between(info.min, info.max).all()
print(fits)This prints False, so int8 is the wrong choice for this column.
Overflow in later arithmetic
A narrow dtype is safe to store but can overflow when you compute with it. Element-wise operations between two int8 columns stay int8:
import pandas as pd
a = pd.Series([100, 100], dtype="int8")
print(a + a)Both results are -56, because 200 does not fit in int8. Downcast columns you only read or group by. Leave columns that feed into sums, products or differences at a wider type, or cast them back up before computing.
Lost precision with float32
float32 keeps about 7 significant decimal digits. Large whole numbers stored as floats lose exactness:
import pandas as pd
s = pd.Series([16777217.0])
print(s.astype("float32"))The value prints as 16777216.0. That is acceptable for sensor readings or percentages. It is not acceptable for money, identifiers, or any column you later compare for exact equality.
Missing values block integer downcasting
A plain int8 or uint8 column cannot hold NaN. A column that contains missing values is stored as float64, and downcast="integer" leaves it as it is. To keep both the missing values and a small footprint, use a nullable integer type. You can pass Int8, Int16, Int32 or UInt8 to astype, for example s.astype("Int16"). These types use a separate boolean mask for the missing entries, so they take slightly more memory than the plain integer types. They are still smaller than float64.
Identifiers and codes
Do not downcast identifier columns just because their current values are small. A user ID column that happens to contain values up to 5,000 today may need int32 next month. If the ID is never used in arithmetic, the safest dtype is often string, as with the zip codes earlier in this tutorial.
Make downcasting part of loading
The cheapest time to pick small dtypes is while reading the file. This avoids creating a full-size int64 frame first. Pass the target types to read_csv:
import io
import pandas as pd
csv = "status,qty,price\nshipped,3,9.5\npending,5,12.25\nshipped,7,3.0\n"
df = pd.read_csv(
io.StringIO(csv),
dtype={"status": "category", "qty": "uint8", "price": "float32"},
)
print(df.dtypes)
print(df.memory_usage(deep=True, index=False))You need to know the safe ranges before you load. A reliable workflow is to read a sample or the full file once with default dtypes, check df.describe() and df.nunique(), then write the dtype dictionary and reuse it in later loads. If a value does not fit the requested integer type, read_csv raises an error, which is safer than the silent wrap of astype.
Summary of the workflow
- Fix correctness first: numbers as numbers, dates as dates, missing values preserved.
- Measure with
df.memory_usage(deep=True)ordf.info(memory_usage="deep"). - Convert repeated text to
categorywhen the unique count is low. - Use
pd.to_numeric(..., downcast=...)for integers, which checks the range for you. - Use
float32only when about 7 digits of precision is enough. - Measure again and compare, and set the same dtypes in
read_csvfor future loads.
Exercise
A DataFrame has a column age with values from 18 to 94 and no missing values. You run df["age"].astype("int8") and later df["age"] * 2 produces negative numbers for some rows. What went wrong, and how would you fix the column and the calculation?
Show answer
The int8 type holds only -128 to 127, so age * 2 overflows for ages above 63 (94 2 = 188 wraps to -68). Storing the ages as int8 was fine, because 94 fits, but the arithmetic stays in int8 and wraps silently. Fix it by casting before the calculation, for example `df["age"].astype("int16") 2. Alternatively keep the column as int16 or uint8. uint8` holds 0 to 255, so it also fits doubled ages up to 127, but a wider type is safer for arithmetic.
Exercise
You have a column country with 250 distinct values across 5 million rows, and a column invoice_id where nearly every one of 5 million values is unique. Which should you convert to category, and how would you confirm that the conversion saved memory?
Show answer
Convert country to category, because the labels repeat heavily and one copy of each label plus a small integer code per row is much smaller than a Python string per row. Leave invoice_id alone, because a category with almost as many labels as rows saves nothing and can cost more. To confirm, compare df["country"].memory_usage(deep=True, index=False) before and after astype("category"), or compare df.memory_usage(deep=True) for the whole frame.