Columns with a small set of repeated string values — status, grade, city — are categorical. The category dtype stores them as integer codes plus a lookup, saving memory and enabling meaningful ordering.
Using categories
df["grade"] = df["grade"].astype("category")df["grade"].cat.categories # the distinct valuesdf.memory_usage(deep=True) # see the savings
Ordered categories
Give categories a meaningful order so comparisons and sorts respect it:
from pandas.api.types import CategoricalDtypeorder = CategoricalDtype(["low", "mid", "high"], ordered=True)df["tier"] = df["tier"].astype(order)df[df["tier"] > "low"] # now comparisons are meaningful
Key takeaways
- 01The category dtype stores repeated strings as integer codes — big memory savings.
- 02.cat.categories lists the distinct values.
- 03Ordered categories give a natural rank so comparisons/sorts respect it.
- 04Use it for low-cardinality columns like status, grade or tier.
