Categorical dtype
The category dtype stores repeated text once and points to it, saving memory and speeding up grouping.
In this page:
Syntax
df["column"] = df["column"].astype("category")
df["column"].cat.categories
Categorical dtype
astype("category") converts a column with few distinct values into integer codes plus a lookup table. It uses far less memory than object strings and can carry a custom order. Ordered categoricals sort and compare logically.
Note:
Categoricals shine for columns like country, status or size with many repeats.
Example: Categorical dtype
import pandas as pd
s = pd.Series(["low", "high", "medium", "low"] * 1000)
c = s.astype("category")
print(s.memory_usage(deep=True) > c.memory_usage(deep=True))
sizes = pd.Categorical(["M", "S", "L"], categories=["S", "M", "L"], ordered=True)
print(sizes.sort_values().tolist())
# Output:
# True
# ['S', 'M', 'L']
Related Topics
Common Mistakes
- Using category for nearly unique values
- Adding unseen values without extending categories
- Forgetting the order for sorting
Chapter Summary
- category stores repeats as codes
- Saves memory
- Supports custom ordering
- Best for low-cardinality columns
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: