Sub topic 5
Ordered categoricals: comparing and sorting
This chapter assumes you can create a categorical column with astype("category") or CategoricalDtype. It also assumes you know that a categorical stores a fixed list of categories plus integer codes, and that you can read the .cat accessor outputs from the earlier chapters. The chapter covers what the ordered flag changes, how comparisons and sorting behave, and which errors to expect.
Why order needs to be declared
Labels such as "small", "medium" and "large" have a natural order, but pandas can't infer it. An object column sorts alphabetically, which puts "large" before "medium" before "small". That is the reverse of the logical order.
import pandas as pd
sizes = ["small", "large", "medium", "small", "large"]
plain = pd.Series(sizes)
print(plain.sort_values().tolist())
# ['large', 'large', 'medium', 'small', 'small']
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
ordered = pd.Series(sizes, dtype=size_type)
print(ordered.sort_values().tolist())
# ['small', 'small', 'medium', 'large', 'large']The order is the sequence of the categories list, and ordered=True tells pandas that this sequence is meaningful. Internally, small has code 0, medium has code 1 and large has code 2. Pandas compares and sorts those integer codes, not the strings.
Three ways to create an ordered categorical
The same result can come from several constructors. Choose by where your data is at the moment.
import pandas as pd
levels = ["small", "medium", "large"]
data = ["small", "large", "medium", "small"]
a = pd.Series(data, dtype=pd.CategoricalDtype(levels, ordered=True))
b = pd.Series(pd.Categorical(data, categories=levels, ordered=True))
c = pd.Series(data).astype(pd.CategoricalDtype(levels, ordered=True))
print(a.equals(b), b.equals(c)) # True True
print(a.dtype) # category
print(a.cat.ordered) # TrueA reusable CategoricalDtype object is the best choice when several columns, or several files, must share one order. Two columns built from the same dtype object have identical categories, which matters for comparisons later in this chapter.
Comparing values
On an ordered categorical, <, <=, > and >= compare positions in the category list. You can compare against a scalar that is one of the categories, or against another Series with the same 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 < "large").tolist()) # [True, False, True, True]
print((s == "small").tolist()) # [True, False, False, True]
other = pd.Series(["medium"] * 4, dtype=size_type)
print((s > other).tolist()) # [False, True, False, False]Equality (==, !=) works on every categorical, ordered or not. The ordering operators are where the rules get stricter.
Comparisons that raise errors
Pandas refuses comparisons whose meaning is unclear. Each case below raises TypeError.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["small", "large", "medium", "small"], dtype=size_type)
# 1. Scalar that is not a category
try:
s < "huge"
except TypeError:
print("scalar not in categories")
# 2. Another categorical with the same categories in a different order
reverse_type = pd.CategoricalDtype(["large", "medium", "small"], ordered=True)
r = pd.Series(["small"] * 4, dtype=reverse_type)
try:
s < r
except TypeError:
print("different category order")
# 3. An unordered categorical
u = pd.Series(["small", "large"], dtype="category")
try:
u < "small"
except TypeError:
print("not ordered")
# Equality against an unknown scalar does not raise; it is just False
print((s == "huge").tolist()) # [False, False, False, False]The table summarizes what the ordered flag changes.
| Operation | Unordered categorical | Ordered categorical |
|---|---|---|
| `==`, `!=` | Works | Works |
| `<`, `<=`, `>`, `>=` | `TypeError` | Works |
| `min()`, `max()` | `TypeError` | Works |
| `sort_values()` | Sorts by category order | Sorts by category order |
Sorting is the surprising row. An unordered categorical still sorts by the position of its categories, not alphabetically, as long as the category list was set deliberately. The ordered flag mainly decides whether you may ask "is A greater than B" and "what is the largest".
Sorting
sort_values and sort_index use the codes, so the result follows your category order. Ascending and descending both work, and so does sorting a DataFrame by several columns.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.DataFrame({
"size": pd.Series(["small", "large", "medium", "small"], dtype=size_type),
"price": [3, 9, 5, 2],
})
result = df.sort_values(["size", "price"], ascending=[True, False])
print(result.index.tolist()) # [0, 3, 2, 1]
print(df["size"].sort_values(ascending=False).tolist())
# ['large', 'medium', 'small', 'small']Row 0 and row 3 are both "small". The second sort key, price in descending order, puts price 3 (row 0) before price 2 (row 3).
Sorting by code is also cheaper than sorting strings, because integers compare faster. The gain is noticeable on large frames.
A related detail: value_counts(sort=False) returns counts in category order, with unused categories included at zero. That gives you a ready-made frequency table in the logical order.
min, max and statistics
min() and max() return the smallest and largest category that appears in the data, by category order.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["medium", "small", "medium"], dtype=size_type)
print(s.min()) # small
print(s.max()) # mediumThe result is medium, not large, because large is a category but doesn't occur in the data. The maximum is taken over values, not over the category list.
Arithmetic such as mean() or sum() is not defined for categoricals, even ordered ones, because the distance between "small" and "medium" is unknown. If you need numeric summaries, work on the codes yourself and accept the assumption that levels are evenly spaced. For example, s.cat.codes.mean().
Missing values
A missing value has code -1 and belongs to no category, so it has no position in the order. That has two consequences.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
t = pd.Series(["medium", None, "small"], dtype=size_type)
print((t > "small").tolist()) # [True, False, False]
print(t.sort_values().index.tolist()) # [2, 0, 1]
print(t.sort_values(na_position="first").index.tolist()) # [1, 2, 0]
print(t.min(), t.max()) # small mediumAny ordering comparison against a missing value gives False, so t > "small" and t <= "small" are both False for the missing row. These two results do not add up to "all rows". If you filter with t <= "small" and with t > "small" expecting a partition, rows with missing values fall into neither group. Handle them explicitly with t.isna().
Sorting puts missing values last by default. min() and max() skip them.
Changing the order of an existing categorical
Converting with astype("category") and no dtype gives alphabetical categories. Calling as_ordered() on that result only sets the flag. It does not fix the order.
import pandas as pd
sizes = ["small", "large", "medium", "small", "large"]
wrong = pd.Series(sizes).astype("category").cat.as_ordered()
print(list(wrong.cat.categories)) # ['large', 'medium', 'small']
print(wrong.max()) # small <- alphabetical order, not logical
right = pd.Series(sizes).astype("category").cat.reorder_categories(
["small", "medium", "large"], ordered=True
)
print(right.max()) # large
print(right.cat.codes.tolist()) # [0, 2, 1, 0, 2]The wrong Series passes every check except being correct. It runs without errors and returns a plausible-looking maximum.
Use these accessor methods depending on the goal:
as_ordered()andas_unordered()switch the flag and keep the category list as it is.reorder_categories(new_order, ordered=...)changes the order. The new list must contain exactly the same categories, or pandas raisesValueError.set_categories(new_order, ordered=...)can also add or drop categories. Values that are no longer in the list become missing.
Using ordered categoricals with other data
Filtering with a threshold is the most common use. This reads closer to the business rule than comparing codes.
import pandas as pd
grade_type = pd.CategoricalDtype(["D", "C", "B", "A"], ordered=True)
grades = pd.Series(["B", "D", "A", "C", "B"], dtype=grade_type)
passing = grades[grades >= "C"]
print(passing.tolist()) # ['B', 'A', 'C', 'B']Note that the category list runs from lowest to highest, so "D" is the lowest grade. If you list categories in the order people usually say them ("A", "B", "C", "D"), then >= means the opposite of what you intend.
Common mistakes
- Setting the flag without the order, as shown above.
- Listing the categories from highest to lowest and then reading
<as "lower". - Comparing two columns built separately, where one has an extra category or a different order. Build both from the same dtype object, or align them with
set_categoriesfirst. - Expecting
s < "huge"to returnFalsefor an unknown label. It raises, while==returnsFalse. - Forgetting missing values in threshold filters.
- Expecting
max()to return the highest category in the dtype. It returns the highest value present.
Exercise
A column level was created with pd.Series(["low", "high", "mid", "low"]).astype("category").cat.as_ordered(). Why does level.max() return "mid", and what one call fixes it so that "high" is the maximum?
Show answer
astype("category") sorts the categories alphabetically, giving ['high', 'low', 'mid'], and as_ordered() keeps that order, so "mid" is the largest. Because "high" is present in the data, the fix is to set the logical order: level.cat.reorder_categories(["low", "mid", "high"], ordered=True). Then max() returns "high".
Exercise
Given t = pd.Series(["medium", None, "small"], dtype=size_type) with an ordered size_type of small, medium, large, how many rows does t[t <= "medium"] return, and what must you add to keep the missing row as well?
Show answer
It returns 2 rows, the "medium" and "small" rows, because the comparison against the missing value is False. To keep the missing row, use t[(t <= "medium") | t.isna()], which returns 3 rows.