← Back to Pandas Course | Chapter 13: Performance & Best Practices | Lesson 3 of 6

Categorical dtype

The category dtype stores repeated text once and points to it, saving memory and speeding up grouping.

In this page:

  1. Categorical dtype
Syntax
python
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

python
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
  1. Using category for nearly unique values
  2. Adding unseen values without extending categories
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.