Sub topic 16
Counting categorical columns
This chapter assumes you know value_counts, unique, nunique and groupby(...).size() on ordinary columns. It covers how those calls change when a column has the category dtype.
What a categorical column adds
A categorical column stores a fixed list of allowed values, called categories, plus a code for each row. The category list can contain values that never appear in the data. Counting functions must choose between reporting only the values present and reporting every category. For a categorical column, most of them report every category.
import pandas as pd
sizes = pd.Series(
pd.Categorical(
["M", "S", "M", "L", "S", "M"],
categories=["S", "M", "L", "XL"],
ordered=True,
)
)No row holds "XL", but it is still one of the four categories.
value_counts keeps unused categories
print(sizes.value_counts())
print(sizes.value_counts(sort=False))
print(sizes.value_counts().sort_index())The first call lists M 3, S 2, L 1 and XL 0. An ordinary string column would omit XL. The zero is useful when you need a complete table, such as a survey with every answer option shown.
By default the rows are ordered by count. With sort=False, or with sort_index(), the rows follow the order of the categories: S, M, L, XL. For an ordered categorical this is usually the order you want to display.
unique and nunique count only what appears
print(sizes.unique()) # values present: M, S, L
print(sizes.nunique()) # 3
print(len(sizes.cat.categories)) # 4unique returns a Categorical that still lists all four categories, but its values are only the ones found in the data. nunique counts the values found, so it returns 3. To count the declared categories, use len(sizes.cat.categories).
If you do not want unused categories, remove them:
trimmed = sizes.cat.remove_unused_categories()
print(trimmed.value_counts()) # XL no longer appearsGrouping by a categorical column
The same rule applies to groupby. The observed argument controls whether unused categories become groups.
df = pd.DataFrame({
"size": sizes,
"store": ["a", "a", "b", "b", "a", "b"],
})
print(df.groupby("size", observed=False).size()) # includes XL with 0
print(df.groupby("size", observed=True).size()) # only S, M, LPass observed explicitly. Its default is False in current pandas 2.x releases, and pandas has announced that the default will change to True in a future major version. Code that relies on the default may change its output after an upgrade.
The category list also affects pairs of columns. pd.crosstab and DataFrame.value_counts can show unused categories as rows or columns of zeros, depending on the pandas version. Check the output before you build a report on it.
Summary of behavior
| Call | Unused category appears? |
|---|---|
| `value_counts()` | Yes, with count 0 |
| `unique()` | Listed in the categories, not in the values |
| `nunique()` | No |
| `groupby(..., observed=False).size()` | Yes, with count 0 |
| `groupby(..., observed=True).size()` | No |
Common errors
- Reading
nunique()as the number of allowed categories. It counts only the values present. - Seeing a row with count 0 and assuming a bug. It is an unused category.
- Comparing a categorical result to a string-column result and finding extra rows. Convert with
astype(str), or callremove_unused_categories(), to get the same rows.
Exercise
A categorical column has categories ["low", "mid", "high"], but the data contains only "low" and "high". What do value_counts() and nunique() return for the number of rows and the distinct count?
Show answer
value_counts() returns three rows, because "mid" appears with a count of 0. nunique() returns 2, because it counts only the values that appear in the data.