Sub topic 16
Counting Categorical Columns
This chapter covers how the counting tools behave on a column with the category dtype. It assumes you know value_counts, unique, nunique, groupby(...).size() and how missing values are treated, all covered in earlier chapters. The main new point is that a categorical column remembers its full list of allowed values, even when some of them never appear in the data.
What a categorical column is
A categorical column stores each value as a small integer code that points into a fixed list called the categories. The dtype is category. Two reasons to use it:
- It saves memory when a column has few distinct values repeated many times.
- It lets you define the allowed values and their order, for example
S < M < L < XL.
You can convert an existing column with astype("category"). You can also build one explicitly with pd.Categorical and choose the categories yourself.
import pandas as pd
sizes = pd.Categorical(
["M", "S", "M", "L", "S", "M", None],
categories=["S", "M", "L", "XL"],
ordered=True,
)
orders = pd.DataFrame({
"shirt_size": sizes,
"region": ["north", "south", "north", "south", "north", "south", "north"],
})
col = orders["shirt_size"]
print(col.dtype) # category
print(col.cat.categories) # Index(['S', 'M', 'L', 'XL'], dtype='object')The data contains only S, M and L, plus one missing value. The category XL is allowed but never used. The rest of the chapter depends on this gap between the categories and the observed values.
value_counts reports unused categories
On a plain string column, value_counts lists only values that occur. On a categorical column it lists every category, so unused ones appear with a count of 0.
print(col.value_counts())
# shirt_size
# M 3
# S 2
# L 1
# XL 0
# Name: count, dtype: int64This is usually what you want for reporting, because a zero is information. A survey table that silently omits "XL" can look like XL was never an option. If you build a chart or a report from the counts, the zeros keep every bar or row in place.
Missing values behave as in earlier chapters. NaN is never a category, so it is dropped by default. With dropna=False it gets its own row.
print(col.value_counts(dropna=False))
# M 3
# S 2
# L 1
# NaN 1
# XL 0normalize=True divides by the number of non-missing values, here 6. The unused category stays in the result with a proportion of 0.0.
Ordering the result
The default sort is by count, descending. For an ordered category that is rarely the order readers expect. You have two options.
sort=Falsereturns the counts in category order..sort_index()sorts by the index, and for a categorical index that means category order, not alphabetical order.
print(col.value_counts(sort=False))
# S 2
# M 3
# L 1
# XL 0
print(col.value_counts().sort_index())
# same order: S, M, L, XLWith a plain string column, sort_index() would give L, M, S, XL. With the categorical it gives S, M, L, XL, because the sort uses the order you declared. This is the main practical benefit of declaring categories.
unique and nunique count only what is observed
unique and nunique do not follow value_counts here. They look at the values present in the data.
print(col.unique())
# ['M', 'S', 'L', NaN]
# Categories (4, object): ['S' < 'M' < 'L' < 'XL']
print(col.nunique()) # 3
print(col.nunique(dropna=False)) # 4
print(len(col.cat.categories)) # 4Three points:
uniquereturns aCategorical, not a NumPy array. It lists the values in order of first appearance, and the missing value appears in the list.XLdoes not show in the values, but the printedCategoriesline still shows it.nunique()is 3, while the number of categories is 4. If you need the number of allowed values, uselen(col.cat.categories). If you need the number of values that occur, usenunique.
| Question | Expression | Result |
|---|---|---|
| How many sizes are allowed? | `len(col.cat.categories)` | 4 |
| How many sizes occur? | `col.nunique()` | 3 |
| How many rows have a size? | `col.count()` | 6 |
| How many rows have no size? | `col.isna().sum()` | 1 |
Unused categories survive filtering
Filtering rows does not change the category list. After you take a subset, the removed values still appear in value_counts with a count of 0.
north = orders[orders["region"] == "north"]
print(north["shirt_size"].value_counts(sort=False))
# S 1
# M 2
# L 0
# XL 0Here L and XL are not in the north rows, yet they are listed. This surprises people who expect only the values in the subset. If you want only what remains, remove the unused categories first.
trimmed = north["shirt_size"].cat.remove_unused_categories()
print(trimmed.value_counts(sort=False))
# S 1
# M 2Counting inside groups: the observed argument
groupby on a categorical column can produce one group per category, or only groups that have rows. The observed argument controls this.
print(orders.groupby("shirt_size", observed=False).size())
# S 2
# M 3
# L 1
# XL 0
print(orders.groupby("shirt_size", observed=True).size())
# S 2
# M 3
# L 1Rows with a missing size are left out of both results, because groupby drops missing keys by default. You can pass dropna=False to groupby to keep them as a group.
The choice also affects performance and size. Grouping by several categorical columns with observed=False produces every combination of categories. Three columns with 50 categories each give 125,000 groups, almost all of them empty. Use observed=True when you group by more than one categorical column.
The size versus count distinction from the earlier chapter still applies:
print(orders.groupby("region")["shirt_size"].count())
# north 3
# south 3
print(orders.groupby("region")["shirt_size"].nunique())
# north 2
# south 3count skips the one missing value in the north rows, so north has 3, not 4. nunique counts distinct sizes per region, which is 2 for north (M, S) and 3 for south (S, L, M).
Choosing how a count handles unused categories
When to convert to category
Converting is worth it when a column has far fewer distinct values than rows, or when order matters. It is not worth it for columns that are nearly unique, such as IDs, because the category list then costs as much as the data. Counting results also change after conversion, as this chapter showed. Check any code that relied on value_counts listing only the values that occur.
Exercise
A categorical column grade has categories ["A", "B", "C", "D"], and the data contains only A, B and C, with no missing values. What do grade.nunique(), len(grade.value_counts()) and len(grade.cat.categories) return, and why do they differ?
Show answer
grade.nunique() returns 3, because it counts only values that occur. len(grade.value_counts()) returns 4, because value_counts on a categorical column lists every category and gives D a count of 0. len(grade.cat.categories) returns 4, because it is the length of the declared category list. The first answer reflects the data, and the other two reflect the category list.
Exercise
You group orders by shirt_size and region, both categorical, and get a huge result full of zero-count rows. What change fixes this, and why should you set it explicitly?
Show answer
Pass observed=True to groupby, for example orders.groupby(["shirt_size", "region"], observed=True).size(). That keeps only combinations that occur. Setting it explicitly matters because the default changed across pandas versions (False before 3.0, True from 3.0), so the same code could return different results on different installations.