Sub topic 2
Ordered categoricals: comparing and sorting
Assume you know basic Python, can create pandas Series and DataFrames, and understand common pandas dtypes such as object and int64.
Ordered categoricals: comparing and sorting
A categorical stores a fixed set of allowed values. An ordered categorical also stores their logical order. This order can differ from alphabetical order.
import pandas as pd
size_type = pd.CategoricalDtype(
["small", "medium", "large"],
ordered=True,
)
sizes = pd.Series(
["small", "large", "medium", "small"],
dtype=size_type,
)
print((sizes >= "medium").tolist())
print(sizes.max())
print(sizes.sort_values().tolist())The output is:
[False, True, True, False]
large
['small', 'small', 'medium', 'large']Without ordered=True, comparisons such as sizes >= "medium" are invalid. Define the order when it represents a real rule, such as size, priority, or a stage.
Managing categories safely
Use the .cat accessor to change a categorical. Adding a value requires adding its category first. Renaming changes labels without changing their positions.
s = pd.Series(["a", "b", "a"], dtype="category")
s = s.cat.add_categories(["c"])
s.iloc[1] = "c"
s = s.cat.rename_categories({"a": "alpha"})
s = s.cat.remove_unused_categories()
print(s.tolist())
print(list(s.cat.categories))set_categories replaces the complete category list. Values missing from the new list become missing values, so use it carefully.
Missing values in categoricals
A missing categorical value is stored separately from the category list. Its integer code is -1; it is not an additional category. Use isna() to detect it. Do not add "missing" as a category unless that text has a distinct business meaning.
Turning numbers into categories with `cut` and `qcut`
pd.cut puts values into specified intervals. pd.qcut creates intervals containing approximately equal numbers of observations.
ages = pd.Series([5, 17, 30, 64, 80])
groups = pd.cut(
ages,
bins=[0, 18, 65, 120],
labels=["child", "adult", "senior"],
)
print(groups.tolist())
scores = pd.Series([10, 20, 30, 40, 50, 60])
quartiles = pd.qcut(scores, q=3, labels=["low", "mid", "high"])
print(quartiles.tolist())cut is useful when boundaries have domain meaning. Use qcut when you want balanced groups based on the data distribution.
Exercise
Why does s.iloc[1] = "c" require a call to add_categories(["c"]) first?
Show answer
A categorical permits only values in its fixed category list. Adding the category expands that list before assignment.