Sub topic 2
Downcasting Floats and Using Categories
This chapter assumes you can create pandas DataFrames and understand common dtypes such as float64, int64, and object.
Downcasting floats and precision
A float64 value uses 8 bytes. A float32 value uses 4 bytes, but it stores fewer significant digits. Use pd.to_numeric to choose the smallest floating-point dtype that can represent the column.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"score": [0.1, 0.25, 0.75, 0.999999],
"amount": [10.0, 20.0, 30.0, 40.0],
})
before = df.memory_usage(deep=True).sum()
df["score"] = pd.to_numeric(df["score"], downcast="float")
df["amount"] = pd.to_numeric(df["amount"], downcast="float")
after = df.memory_usage(deep=True).sum()
print(df.dtypes)
print(before, after)
assert np.allclose(
df["score"],
[0.1, 0.25, 0.75, 0.999999],
rtol=1e-6,
)float32 is often suitable for measurements, scores, and machine-learning features. It may be unsafe for financial calculations or values requiring exact decimal behavior.
| Dtype | Bytes per value | Approximate precision |
|---|---|---|
| `float32` | 4 | 7 decimal digits |
| `float64` | 8 | 15–16 decimal digits |
Why object strings cost memory
An object column stores references to Python objects. Each string has its own object overhead, in addition to its characters. Therefore, repeated strings can consume much more memory than their visible text suggests. Use memory_usage(deep=True) to count the referenced string data.
Converting repetitive strings to category
The category dtype stores each distinct string once. Each row then stores a small integer code referring to that shared value.
df = pd.DataFrame({"country": ["US", "DE", "US", "FR", "US"]})
print(df.memory_usage(deep=True))
df["country"] = df["country"].astype("category")
print(df.memory_usage(deep=True))
print(df["country"].cat.categories)
print(df["country"].cat.codes)Cardinality trade-offs
Cardinality is the number of distinct values in a column. Categories usually help when cardinality is low compared with the row count.
- Good fit: country, status, product type, or repeated labels.
- Poor fit: unique IDs, timestamps, URLs, or nearly unique text.
- Check downstream code because adding unseen values requires category handling, and some operations behave differently with categorical data.
Exercise
Why can converting a unique-ID column to category fail to save memory?
Show answer
Each ID still needs a distinct category, so the category dictionary and codes can cost as much as or more than the original strings.