Skip to main content
Albero Academy

Categorical Data

The category dtype for memory savings and ordered categories.

Time Series & Advanced7 min

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

category dtype
df["grade"] = df["grade"].astype("category")
df["grade"].cat.categories # the distinct values
df.memory_usage(deep=True) # see the savings

Ordered categories

Give categories a meaningful order so comparisons and sorts respect it:

ordered comparisons
from pandas.api.types import CategoricalDtype
order = CategoricalDtype(["low", "mid", "high"], ordered=True)
df["tier"] = df["tier"].astype(order)
df[df["tier"] > "low"] # now comparisons are meaningful

Key takeaways

  1. 01The category dtype stores repeated strings as integer codes — big memory savings.
  2. 02.cat.categories lists the distinct values.
  3. 03Ordered categories give a natural rank so comparisons/sorts respect it.
  4. 04Use it for low-cardinality columns like status, grade or tier.

Finished this chapter?

Mark it complete to track your progress through Pandas.