When a text column has few distinct values repeated many times (a status, a city, a programme), storing it as a category saves large amounts of memory and speeds up grouping. On big datasets, choosing types deliberately is the difference between fitting in RAM and not.
The category dtype
A category stores each distinct value once and represents rows as small integer codes pointing at it:
df["programme"] = df["programme"].astype("category")df["programme"].cat.categories # the distinct valuesdf["programme"].cat.codes # the integer code per row# On a column with few uniques but many rows, memory can drop 10×+.
Ordered categories
Categories can carry a meaningful order, so comparisons and sorting respect it (Low < Mid < High, not alphabetical):
from pandas.api.types import CategoricalDtypeband = CategoricalDtype(["Low", "Mid", "High"], ordered=True)df["tier"] = df["tier"].astype(band)df[df["tier"] > "Low"] # comparisons now make sensedf.sort_values("tier") # sorts Low → Mid → High, not alphabetically
Measuring & cutting memory
df.memory_usage(deep=True) # bytes per column (deep counts strings)df.info(memory_usage="deep") # total footprint# Biggest wins: object → category for low-cardinality text columns.
Efficient numeric types
Numbers default to 64-bit; often 32- or even 8-bit is plenty and halves (or better) the memory:
df["count"] = pd.to_numeric(df["count"], downcast="integer") # int64 → int8/16…df["price"] = pd.to_numeric(df["price"], downcast="float") # float64 → float32# Read big CSVs with explicit dtypes to avoid the wasteful defaultspd.read_csv("big.csv", dtype={"programme": "category", "count": "int32"})
Practice
Convert a low-cardinality text column to category and compare memory_usage(deep=True) before and after. Make an ordered category for a rating column and sort by it. Downcast a numeric column and confirm the values are unchanged.
Key takeaways
- 01The category dtype stores each distinct value once — big memory savings on repeated text.
- 02cat.categories / cat.codes expose the mapping; grouping on categories is faster too.
- 03Ordered categories make comparisons and sorting follow a meaningful order, not alphabetical.
- 04memory_usage(deep=True) and info(memory_usage="deep") show where the bytes go.
- 05Downcast numerics (int8/16/32, float32) and set dtypes in read_csv — but ensure the type fits future values.
