Text sorts alphabetically, which is wrong for sizes (L, M, S, XL) and ratings (Happy, Neutral, Unhappy...). A categorical column stores the allowed values in your order:
survey["size"] = pd.Categorical(survey["size"], categories=["S", "M", "L", "XL"], ordered=True)
With ordered=True:
sort_values("size") sorts S, M, L, XL.
- Comparisons follow the order:
survey[survey["size"] >= "L"] keeps L and XL.
value_counts(sort=False) lists the categories in their order.
Categories you list but nobody chose still exist. In pandas 3, groupby shows only the categories that occur (observed=True is the default); pass observed=False to include the empty ones with a count of 0.
Categoricals also save memory when a column repeats a few values many times, which the performance unit returns to.