Sub topic 5
Ordered categoricals: comparing and sorting
This chapter assumes you can create a categorical column with astype("category") and know that a categorical holds a fixed set of categories plus integer codes. If not, review the earlier chapters on creating categoricals and on categories and codes.
Why order matters
A plain categorical has no order. Pandas sorts it by the order of its categories, and by default that order is alphabetical, because astype("category") sorts the unique values. For sizes, that gives large, medium, small, which is wrong for most uses. It also refuses comparisons like "greater than", because the categories have no meaning as a ranking.
An ordered categorical states that the categories have a rank. The order of the category list is the rank, from lowest to highest.
Defining an ordered dtype
Create a CategoricalDtype with the categories listed in rank order and ordered=True. Then pass it as the dtype.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["small", "large", "medium", "small"], dtype=size_type)
print((s >= "medium").tolist()) # [False, True, True, False]
print(s.max()) # large
print(s.sort_values().tolist()) # ['small', 'small', 'medium', 'large']Comparisons use the category rank. The string "medium" works on the right side because it is one of the categories. Sorting also follows the rank, so sort_values() gives small, medium, large instead of alphabetical order.
You can order an existing column in two ways:
s.cat.as_ordered()marks the current category order as meaningful. Use it only if the categories are already in the right order.s.cat.set_categories(["small", "medium", "large"], ordered=True)sets the order and the ordered flag in one step.
Use s.cat.as_unordered() to turn ordering off.
What ordering enables
| Operation | Unordered | Ordered |
|---|---|---|
| `s.sort_values()` | By category order | By category order |
| `s < "medium"` against a scalar | Raises `TypeError` | Works |
| `s.min()`, `s.max()` | Raises `TypeError` | Works |
| `==` and `!=` | Works | Works |
Sorting follows the category order in both cases. Ordering adds ranking operations. This difference is why the flag matters even when you only sort.
Ordered categoricals also work with idxmax, nlargest, and pd.cut with ordered=True, and they carry their order into groupby results, so group keys appear in rank order.
Comparing two categoricals
You can compare two ordered categoricals element by element, but both must have the same categories in the same order. Pandas raises a TypeError if the category lists differ.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
ordered = pd.Series(["small", "large", "medium"], dtype=size_type)
limit = pd.Series(["medium", "medium", "medium"], dtype=size_type)
print((ordered > limit).tolist()) # [False, True, False]Comparing against a scalar that is not in the categories also raises an error. Check the value first or add it to the categories.
Common errors
- Comparing an unordered categorical.
TypeError: Unordered Categoricals can only compare equality or not. Setordered=Trueon the dtype. - Mismatched categories. Two columns with the same labels in a different order are different dtypes. Build both from one shared
CategoricalDtypeobject. - Wrong rank order. Category lists are taken as written. Typing
["small", "large", "medium"]makes large lower than medium. - Values outside the categories. A value not in the list becomes
NaNwhen you build the column. Checks.isna().sum()after conversion.
Exercise
A Series has dtype CategoricalDtype(["low", "high", "medium"], ordered=True). What does s.max() return when s holds ["low", "medium", "high"], and how do you correct the result so it matches the real meaning of the levels?
Show answer
It returns "medium", because the category list ranks medium above high. Fix it by calling s.cat.reorder_categories(["low", "medium", "high"], ordered=True), or by building the dtype with the categories in the right order. After that, s.max() returns "high".