Sub topic 12
Putting it together in a reusable function
This chapter combines the earlier techniques into one function and adds a check that the result still matches the original. It assumes you can measure memory with memory_usage(deep=True), downcast with pd.to_numeric, and convert strings to category.
The decision per column
The function looks at each column's dtype and applies one rule. Columns that fit no rule are left unchanged.
The cardinality test in the string branch comes from the earlier chapter on categories. A column where nearly every value is different gains nothing from category, because the table of categories grows as large as the data.
The function
import numpy as np
import pandas as pd
def shrink(df, max_unique_ratio=0.5):
out = df.copy()
for col in out.select_dtypes(include="integer").columns:
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="float").columns:
out[col] = pd.to_numeric(out[col], downcast="float")
for col in out.select_dtypes(include=["object", "string"]).columns:
if out[col].nunique() < max_unique_ratio * len(out):
out[col] = out[col].astype("category")
return outThe function works on a copy, so the caller's DataFrame is never modified. It uses downcast="integer" for every integer column, which can produce signed types such as int8. If a column never holds negative values, you can pass downcast="unsigned" for it separately.
A verification function
A shrunk DataFrame should hold the same values as the original. Integers and strings must match exactly. Floats are compared with a tolerance, because float32 keeps only about seven significant digits.
def check_shrunk(original, smaller, rtol=1e-6):
assert original.shape == smaller.shape
assert (original.columns == smaller.columns).all()
for col in original.columns:
a, b = original[col], smaller[col]
if a.dtype.kind == "f":
assert np.allclose(a, b, rtol=rtol, equal_nan=True), col
else:
assert np.array_equal(a.to_numpy(), b.to_numpy()), colRunning it end to end
This example includes an email column where every value is unique. The function should leave that column as object.
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
"email": [f"user{i}@example.com" for i in range(n)],
})
small = shrink(df)
check_shrunk(df, small)
print(small.dtypes)
before = df.memory_usage(deep=True).sum()
after = small.memory_usage(deep=True).sum()
print(f"{before:,} -> {after:,} bytes ({after / before:.0%} of original)")Expect user_id as uint16-range data stored in a signed type (int32, since 50,000 exceeds the int16 maximum of 32,767), age as int8, score as float32, country as category, and email still as object. The email column dominates the total, so the overall saving is smaller than the saving on the other columns.
Limits to keep in mind
- Future values may not fit.
int8holds -128 to 127. If you later assign 200 to anagecolumn stored asint8, you get an error or a wrapped value, depending on your pandas version. Downcast columns whose range you know will stay stable. - Categoricals reject new values. Assigning a value that is not in
categoriesraises an error or producesNaN. Add the category first, or convert back toobjectbefore editing. - Group with
observed=True. When you callgroupbyon a categorical column, passobserved=Trueso unused categories do not appear as empty groups. - Float precision changes. Sums over float32 columns can differ slightly from float64 sums. If exact totals matter, keep those columns as float64.
Exercise
Exercise
You call shrink(df) on a DataFrame with 1,000 rows. A string column "city" has 600 distinct values. With the default maxuniqueratio=0.5, does it become category? What would you change to convert it, and why might you not want to?
Show answer
No. 600 is not less than 0.5 * 1,000 = 500, so the column stays object. Passing maxuniqueratio=0.7 would convert it. You might not want to, because with 600 distinct values in 1,000 rows the category table is nearly as large as the data. The memory saving is small, and categorical columns add restrictions on new values and on grouping.
Exercise
Why does checkshrunk compare float columns with np.allclose but compare other columns with np.arrayequal?
Show answer
Downcasting a float64 column to float32 rounds each value to about seven significant digits, so exact equality would fail. Integer downcasting and category conversion keep every value exactly, so an exact comparison is the correct test and will catch any real change.