Skip to main content
Albero Academy

Categorical Data & Memory

Shrink memory and gain speed with the category dtype, order categories meaningfully, and choose efficient types for large data.

Chapter 9Pandas14 min readBeginner friendly
  • #Pandas
  • #Categorical
  • #Memory

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:

convert to category
df["programme"] = df["programme"].astype("category")
df["programme"].cat.categories # the distinct values
df["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):

ordered categories
from pandas.api.types import CategoricalDtype
band = CategoricalDtype(["Low", "Mid", "High"], ordered=True)
df["tier"] = df["tier"].astype(band)
df[df["tier"] > "Low"] # comparisons now make sense
df.sort_values("tier") # sorts Low → Mid → High, not alphabetically

Measuring & cutting memory

see where the bytes go
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:

downcasting numbers
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 defaults
pd.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

  1. 01The category dtype stores each distinct value once — big memory savings on repeated text.
  2. 02cat.categories / cat.codes expose the mapping; grouping on categories is faster too.
  3. 03Ordered categories make comparisons and sorting follow a meaningful order, not alphabetical.
  4. 04memory_usage(deep=True) and info(memory_usage="deep") show where the bytes go.
  5. 05Downcast numerics (int8/16/32, float32) and set dtypes in read_csv — but ensure the type fits future values.