Sub topic 12
Putting it together in a reusable function
This chapter assumes you have read the earlier chapters on measuring memory with memory_usage(deep=True), integer and float downcasting, and the category dtype. You should be comfortable with pd.to_numeric, select_dtypes, and astype. Here you combine those steps into one function you can run on any DataFrame, add a safety check and a memory report, and learn where a generic function can go wrong.
What the function must do
A one-off cell that shrinks three known columns is easy to write. A reusable function has to make decisions on its own, so it needs to answer four questions:
- Which columns are integers, floats, or strings?
- How far can each numeric column shrink without losing information?
- Which string columns have few enough distinct values to pay off as categories?
- How do you know the result still holds the same data?
The flow below is the one the function in this chapter follows.
The shrink function
The version from the earlier chapter downcasts everything it finds. This version adds three controls. An exclude list protects columns you do not want touched. A tolerance check on floats means a column is converted only if the lossy conversion stays close to the original. Both thresholds are parameters, so callers can tighten or loosen them.
import numpy as np
import pandas as pd
def shrink(df, max_unique_ratio=0.5, float_rtol=1e-6, exclude=()):
"""Return a smaller copy of df. Columns named in exclude are left as they are."""
out = df.copy()
for col in out.select_dtypes(include="integer").columns:
if col in exclude:
continue
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="float").columns:
if col in exclude:
continue
candidate = pd.to_numeric(out[col], downcast="float")
if np.allclose(candidate, out[col], rtol=float_rtol, equal_nan=True):
out[col] = candidate
for col in out.select_dtypes(include=["object", "string"]).columns:
if col in exclude:
continue
if out[col].nunique() < max_unique_ratio * len(out):
out[col] = out[col].astype("category")
return outSome details in this function are deliberate:
df.copy()means the caller's DataFrame is never modified. Memory peaks briefly at roughly the size of both frames. If the original is already near your memory limit, shrink at load time instead (see the last section).downcast="integer"picks a signed type, which also handles negative values. If you know a column is non-negative,downcast="unsigned"can reach a type with twice the maximum, such asuint8(0 to 255) instead ofint8(up to 127).np.allclose(..., equal_nan=True)treats missing values as equal to each other. Without it, any column with a NaN would fail the check and stayfloat64.nunique()ignores missing values by default. A column of mostly unique strings with a few NaN still has a high ratio and is correctly left alone.- The function assumes NumPy-backed columns. Columns with nullable extension dtypes such as
Int64orFloat64may behave differently, so test them separately before relying on this function.
Verifying the result
A shrink function that silently changes data is worse than no shrink function. The checker below compares every column of the original and the result. Floats are compared with a tolerance, because float32 cannot hold every float64 value. Everything else must match exactly.
def check_same(before, after, float_rtol=1e-6):
"""Raise ValueError if after does not hold the same data as before."""
if list(before.columns) != list(after.columns):
raise ValueError("Column names or order changed")
if not before.index.equals(after.index):
raise ValueError("Index changed")
for col in before.columns:
a, b = before[col], after[col]
if pd.api.types.is_float_dtype(a):
same = np.allclose(
a.to_numpy(dtype="float64"),
b.to_numpy(dtype="float64"),
rtol=float_rtol,
equal_nan=True,
)
else:
same = a.equals(b.astype(a.dtype))
if not same:
raise ValueError(f"Column {col!r} changed during shrinking")
def memory_report(before, after):
"""Per-column memory in KB before and after, with the percentage saved."""
b = before.memory_usage(deep=True)
a = after.memory_usage(deep=True)
report = pd.DataFrame({"before_kb": b / 1024, "after_kb": a / 1024})
report["saved_pct"] = 100 * (1 - report["after_kb"] / report["before_kb"])
return report.round(1)For non-float columns, b.astype(a.dtype) converts the shrunk column back to the original dtype, and equals then checks dtype and values together. That handles integers (int8 back to int64) and categories (back to object) with one line. equals also treats NaN in the same position as equal.
Running it on real-sized data
This block rebuilds the sample frame from earlier in the tutorial and runs the whole pipeline.
import numpy as np
import pandas as pd
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),
})
shrunk = shrink(df)
check_same(df, shrunk)
print(shrunk.dtypes)
print(memory_report(df, shrunk))
print(df.memory_usage(deep=True).sum(), shrunk.memory_usage(deep=True).sum())Run this after pasting in the two function definitions from above, or save them in a module and import them. You should see user_id become uint16 or int32, depending on the downcast mode. age becomes int8, score becomes float32, and country becomes category. The country column shows the largest saving, because it goes from one Python string reference per row to one small integer code per row. The exact byte counts depend on your pandas and Python versions, so compare the before and after totals on your machine rather than expecting fixed numbers.
What can go wrong
Arithmetic on small integers can overflow
Downcasting is safe for storage, but it changes the dtype that later arithmetic operates on. NumPy integer arithmetic on small types wraps around silently instead of raising an error.
import pandas as pd
ages = pd.Series([100, 120], dtype="int8")
print((ages + ages).tolist())
print((ages.astype("int64") + ages.astype("int64")).tolist())The first line prints [-56, -16], because 200 and 240 do not fit in int8. The second prints [200, 240]. If a column will be multiplied, summed row by row, or used in feature engineering, either exclude it or cast up before the arithmetic. Aggregations such as .sum() and .mean() are generally safe, because pandas accumulates in a wider type.
Columns that are really identifiers or money
Float downcasting to float32 gives about 7 significant digits. That is fine for a score or a sensor reading. It is not fine for a price total in the millions that must match a ledger to the cent, or for a large numeric ID stored as a float. Put these columns in exclude.
Categories and later operations
The pitfalls from the earlier chapter apply to every column the function converts. These three come up most often in pipelines:
- New values. Assigning a value that is not in the categories raises an error or produces NaN, depending on the operation.
- Concatenation. Concatenating two frames whose categorical columns have different categories falls back to
object, and the memory saving disappears. Usepd.api.types.union_categoricalsor give both frames the same fixed categories. - Groupby. Without
observed=True, a groupby on a categorical column can return rows for categories that do not appear in the data. Passobserved=Trueunless you want those empty groups.
means = shrunk.groupby("country", observed=True)["score"].mean()
print(means)The ratio threshold is a heuristic
A max_unique_ratio of 0.5 is a reasonable default, not a law. Categories pay off most when the number of distinct values is far below the number of rows, often under a few percent. Values near 0.5 save little memory and can make some operations slower. If you shrink many frames, lower the ratio, for example to 0.1, and measure.
Reusing the result: apply the schema at load time
Shrinking after loading means you still pay for the large frame once. After you shrink a representative sample, record the dtypes and pass them to read_csv for every later load.
import pandas as pd
from io import StringIO
schema = {"age": "int8", "country": "category"}
csv = StringIO("age,country\n34,US\n29,DE\n41,US\n")
small = pd.read_csv(csv, dtype=schema)
print(small.dtypes)Two warnings apply when you reuse a schema. First, a value outside the dtype's range, such as an age of 300 for int8, makes read_csv raise an error. That is a useful failure, because it tells you the schema is out of date. Second, a schema built from one month of data may not fit the next month. Treat the schema as something you validate, not as a constant.
Summary of the design
| Concern | How the function handles it |
|---|---|
| Original data modified | Works on `df.copy()` |
| Float precision loss | Converts only if `np.allclose` passes at `float_rtol` |
| Columns that must not change | `exclude` argument |
| Categories that do not pay off | `max_unique_ratio` threshold |
| Silent data corruption | `check_same` raises `ValueError` |
| Saving not visible | `memory_report` shows per-column results |
Exercise
A non-negative integer column holds values from 0 to 70,000. You call pd.to_numeric(col, downcast="unsigned"). Which dtype do you get, and why not uint16?
Show answer
You get uint32. The largest value uint16 can hold is 65,535, and 70,000 is larger, so pandas moves up to the next unsigned type, which holds values up to about 4.29 billion.
Exercise
After shrinking, a colleague computes df["age"] * 3 on an int8 column holding the value 90 and gets a negative number. Explain the cause and give two ways to avoid it.
Show answer
90 3 = 270 does not fit in int8, whose maximum is 127, so the result wraps around silently. Either cast the column to a wider type before the arithmetic, for example df["age"].astype("int64") 3, or pass "age" in the exclude list so shrink leaves it as int64.
Exercise
You apply shrink to two monthly DataFrames, then concatenate them with pd.concat. The country column becomes object and memory use jumps. Why, and how do you fix it?
Show answer
Each frame's country column has its own set of categories. When the categories differ, pd.concat cannot keep a single categorical dtype and falls back to object. Fix it by using pd.api.types.union_categoricals on the column, or by casting both frames to the same CategoricalDtype with a fixed list of categories before concatenating.