Sub topic 7
Missing values in categoricals
This chapter assumes you know how a categorical stores categories and integer codes, and that you can use .cat, isna, and fillna on ordinary Series.
Missing values are not categories
A categorical has a fixed list of categories. A missing value (NaN, None, or pd.NA) is never part of that list. pandas stores a missing entry as the integer code -1, which points to no category.
import pandas as pd
s = pd.Series(["a", None, "b", "a"], dtype="category")
print(s.cat.categories.tolist()) # ['a', 'b']
print(s.cat.codes.tolist()) # [0, -1, 1, 0]
print(s.isna().tolist()) # [False, True, False, False]The missing entry did not create a third category. The -1 code is how pandas records "no value here".
Detecting and counting missing values
The usual tools work as they do on other dtypes. isna(), notna(), and dropna() behave as you expect.
value_counts() drops missing values by default. Pass dropna=False to count them, which gives a missing-value row in the result.
import pandas as pd
s = pd.Series(["a", None, "b", "a"], dtype="category")
print(s.value_counts())
print(s.value_counts(dropna=False))Categories that never occur still appear with a count of 0. That is a categorical-specific behavior and it comes back in the groupby chapter.
Filling missing values
fillna on a categorical only accepts a value that is already a category. Anything else fails, because the category list is fixed until you change it.
import pandas as pd
s = pd.Series(["a", None, "b", "a"], dtype="category")
try:
s.fillna("missing")
except (TypeError, ValueError) as err:
print("fillna failed:", type(err).__name__)
filled = s.cat.add_categories("missing").fillna("missing")
print(filled.tolist()) # ['a', 'missing', 'b', 'a']The error type depends on your pandas version, so the example catches both. The fix is the same in every version. Add the category first, then fill.
Fill with an existing category or a new label
Choose based on what the gap means.
- Fill with an existing category when the gap really means that value. For example, a missing
"status"may mean"unknown", and"unknown"is already a category. - Add a new category such as
"missing"when you want the gap to stay visible as its own group in counts and plots. - Leave the gap as missing when it carries information and later code can handle it.
Filling with a label turns a missing value into a normal category. After that, isna() returns False for those rows. Any code that relied on isna() to find them will miss them.
Missing values in ordered categoricals
A missing value has no position in the order. In an ordered categorical, comparisons involving a missing entry return False, and reductions such as min and max skip it by default.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["small", None, "large"], dtype=size_type)
print((s >= "medium").tolist()) # [False, False, True]
print(s.max()) # largeA False from a comparison therefore does not mean "less than". It can also mean "unknown". If the difference matters, combine the comparison with s.notna().
Common mistakes
- Looking for
NaNins.cat.categories. It is never there, so useisna()or check for code-1. - Assigning a new string to a gap without adding the category first. The assignment raises an error.
- Passing
dropna=Falseonly in some places, so counts disagree between reports. - Using the
-1code as a feature in a model without noticing that it means "missing". Encoding for models comes up in a later chapter.
Exercise
A Series s = pd.Series(["x", None, "y"], dtype="category") is given. Write the code that makes the missing entry appear as the label "none" in s.tolist(), and explain why s.fillna("none") alone fails.
Show answer
Use s.cat.add_categories("none").fillna("none"). The plain s.fillna("none") fails because "none" is not in the categories, and a categorical only accepts values from its fixed category list. Adding the category first makes the fill valid. The result is ['x', 'none', 'y'].
Exercise
What integer code does pandas store for a missing entry in a categorical, and does the missing value appear in .cat.categories?
Show answer
pandas stores the code -1. The missing value does not appear in .cat.categories, because missing values are never categories.