Skip to content

Pandas Categorical Ordered Quick Fix

DodaTech Updated 2026-06-26 2 min read

You will learn how to create ordered categorical columns in pandas so that sorting, comparison operators, and min/max respect your category hierarchy instead of falling back to alphabetical order.

The Problem

By default, pandas categoricals are unordered. Sorting a categorical column sorts categories alphabetically, ignoring any natural hierarchy like ["low", "medium", "high"]. This leads to incorrect results in summaries, plots, and feature engineering.

The Wrong Way

import pandas as pd
s = pd.Series(["high", "low", "medium"], dtype="category")
print(s.sort_values())

Output:

1     low
2     medium
0     high
dtype: category
Categories (3, object): ['high', 'low', 'medium']

Alphabetical sorting puts high before low, which is semantically wrong.

The Right Way

from pandas.api.types import CategoricalDtype
cat_ord = CategoricalDtype(categories=["low", "medium", "high"], ordered=True)
s = pd.Series(["high", "low", "medium"], dtype=cat_ord)
print(s.sort_values())
print(s.min(), "<", s.max())

Output:

1     low
2     medium
0     high
dtype: category
Categories (3, object): ['low' < 'medium' < 'high']
low < high

Sorting and comparisons now follow the defined category order.

Step-by-Step Fix

1. Define a CategoricalDtype with ordered=True

dtype = CategoricalDtype(categories=["cold", "warm", "hot"], ordered=True)

2. Apply to your data

temps = pd.Series(["hot", "cold", "warm"], dtype=dtype)

3. Use comparison operators

print(temps > "cold")  # True for warm and hot

Prevention Tips

  • Set ordered=True whenever categories have a natural rank (e.g., sizes, ratings, priority levels)
  • Always specify categories explicitly in CategoricalDtype to fix the order
  • Use .cat.reorder_categories() to change order on existing categoricals
  • Verify ordering with .cat.ordered which returns a boolean

Common Mistakes

  1. Assuming pd.Categorical() preserves insertion order -- it does not unless categories is explicitly provided
  2. Using sort_values() on unordered categoricals -- yields alphabetical or insertion order
  3. Comparing categoricals with < and > on unordered types -- raises TypeError

These mistakes appear frequently in real-world pandas code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

FAQ

### How do I check if a categorical is ordered?

Use s.cat.ordered which returns True or False.

Can I make an existing categorical ordered?

Yes: s.cat.as_ordered() returns a new ordered categorical.

What operations respect categorical ordering?

Sorting, min(), max(), comparison operators (<, >, <=, >=), and groupby order all respect the defined category order.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tools integrate seamlessly with pandas for enhanced productivity and security.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro