Sub topic 7
Missing values in categoricals
This chapter assumes you can build a categorical column with astype("category") or CategoricalDtype. It also assumes you know the .cat accessor, the difference between categories and codes, and basic isna and fillna use on ordinary columns. Here you will see how a categorical represents a missing value, which operations skip it, and how to handle it deliberately.
Missing is not a category
A categorical stores a fixed list of categories and one integer code per row. A missing value does not appear in that list. It is stored as the code -1, which points at no category.
import pandas as pd
s = pd.Series(["small", "large", None, "small"], dtype="category")
print(list(s.cat.categories)) # ['large', 'small']
print(s.cat.codes.tolist()) # [1, 0, -1, 1]
print(s.isna().tolist()) # [False, False, True, False]
print(s.dtype) # categoryThe categories are only large and small. The third row has code -1, and isna() reports it as missing. Because the missing marker lives in the codes, you cannot add NaN to the categories. Pandas rejects a category list that contains nulls.
import numpy as np
import pandas as pd
try:
pd.Categorical(["a", "b"], categories=["a", np.nan])
except ValueError as err:
print("rejected:", err)Missing data therefore has a different status from a real label. Every operation on a categorical has to decide what to do with -1, and the sections below cover those decisions.
How common operations treat missing values
Most operations that summarize a categorical skip missing values unless you ask otherwise. Here is the default behavior of the operations you will use most.
| Operation | Default behavior with missing values | How to change it |
|---|---|---|
| `value_counts()` | Missing rows are not counted | `dropna=False` adds a `NaN` row |
| `groupby(key)` | Rows with a missing key are dropped | `dropna=False` keeps a `NaN` group |
| `sort_values()` | Missing values go last | `na_position="first"` |
| `max()` and `min()` on ordered data | Missing values are skipped | `skipna=False` returns `NaN` |
| Comparison such as `s >= "medium"` | Gives `False` at missing rows | Combine with `isna()` |
| `pd.get_dummies(s)` | Missing rows get all zeros | `dummy_na=True` adds a column |
Here is value_counts with both settings.
import pandas as pd
s = pd.Series(["small", "large", None, "small"], dtype="category")
print(s.value_counts()) # small: 2, large: 1
print(s.value_counts(dropna=False)) # adds a NaN row with count 1The silent skipping is convenient, but it can hide gaps. If you report percentages from value_counts(), the denominator excludes missing rows. Compare the total with len(s) when the number of missing rows matters.
Filling missing values requires an existing category
On an object column, fillna("unknown") always works. On a categorical it works only if "unknown" is already one of the categories. A categorical can hold only its declared values, so filling with anything else fails.
import pandas as pd
s = pd.Series(["small", "large", None, "small"], dtype="category")
try:
s.fillna("unknown")
except (TypeError, ValueError) as err:
print("fillna failed:", type(err).__name__)
filled = s.cat.add_categories("unknown").fillna("unknown")
print(filled.tolist()) # ['small', 'large', 'unknown', 'small']
print(list(filled.cat.categories)) # ['large', 'small', 'unknown']The error type depends on your pandas version, so the example catches both TypeError and ValueError. Add the category first, then fill.
Filling changes the meaning of the column. The new unknown label is a real category now. It appears in value_counts(), in groupby, and in one-hot encoding. On an ordered categorical it also gets a position in the order, which is usually wrong. If the column is ordered, decide whether an unknown value belongs between medium and large. Often it is better to leave the value missing.
You can also fill with an existing category, for example the most common one.
import pandas as pd
s = pd.Series(["small", "large", None, "small"], dtype="category")
mode_value = s.mode().iloc[0]
print(s.fillna(mode_value).tolist()) # ['small', 'large', 'small', 'small']This is imputation, and it has the same statistical consequences as imputing in any other dtype.
Sentinel values become categories
Data files often mark missing values with a placeholder such as "?", "-", or "unknown". If you convert such a column to categorical without handling the placeholder, it becomes a regular category. Your counts then include a label that means "no data".
There are two clean fixes. The first removes the placeholder from the categories. Rows that used it become missing.
import pandas as pd
raw = pd.Series(["a", "?", "b", "?", "a"], dtype="category")
clean = raw.cat.remove_categories("?")
print(clean.tolist()) # ['a', nan, 'b', nan, 'a']
print(list(clean.cat.categories)) # ['a', 'b']remove_categories is the one .cat method that turns existing values into missing values. Other category edits never do that.
The second fix tells the reader about the placeholder, so it never becomes a category. This is better when you load a file.
import io
import pandas as pd
csv = "id,grade\n1,A\n2,?\n3,B\n4,n/a\n"
df = pd.read_csv(
io.StringIO(csv),
dtype={"grade": "category"},
na_values=["?"],
)
print(df["grade"].tolist()) # ['A', nan, 'B', nan]
print(list(df["grade"].cat.categories)) # ['A', 'B']The na_values list adds to pandas' built-in markers, and n/a is one of those. Both placeholders end up as missing, and neither is a category.
Ordered categoricals and missing values
Missing values have no position in an order. For an ordered categorical, that has consequences for comparison and for min and max.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
t = pd.Series(["small", None, "large"], dtype=size_type)
print((t >= "medium").tolist()) # [False, False, True]
print(t.max()) # large
print(t.isna().tolist()) # [False, True, False]The comparison returns False for the missing row, even though that row is not "less than medium" either. The row is neither above nor below. If you filter with t >= "medium", missing rows are excluded. If you filter with ~(t >= "medium"), missing rows are included, which may surprise you. Write the missing case explicitly:
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
t = pd.Series(["small", None, "large"], dtype=size_type)
low_or_unknown = t.isna() | (t < "medium")
print(low_or_unknown.tolist()) # [True, True, False]Missing values in groupby
When a categorical is the grouping key, rows with a missing key are dropped by default. Pass dropna=False to keep them as their own group.
import pandas as pd
df = pd.DataFrame({
"g": pd.Categorical(["x", "y", None, "x"]),
"v": [1, 2, 3, 4],
})
print(df.groupby("g", observed=True)["v"].sum()) # x: 5, y: 2
print(df.groupby("g", observed=True, dropna=False)["v"].sum()) # adds NaN: 3The first call silently drops the row with v = 3. If totals must reconcile with the source table, use dropna=False or check for missing keys first. The observed argument is a separate setting, covered in the groupby chapter.
The -1 code pitfall
The code -1 becomes a problem when you use cat.codes for your own lookups. NumPy treats -1 as "the last element", so a missing value silently maps to the last label.
import numpy as np
import pandas as pd
s = pd.Series(["a", None, "b"], dtype="category")
codes = s.cat.codes.to_numpy()
lookup = np.array(["first", "second"])
print(codes) # [ 0 -1 1]
print(lookup[codes]) # ['first' 'second' 'second']
print(np.where(codes >= 0, lookup[codes], "missing")) # ['first' 'missing' 'second']The second line shows the bug: the missing row is labeled second with no error. The third line guards against it. The same applies when you pass codes to a model. A model that treats the codes as numbers sees -1 as a value below every real category. The encoding chapter covers better options, but the rule here is to test codes == -1 before you trust the codes.
Deciding what to do
The right treatment depends on what a missing value means in your data. This flow summarizes the choices.
A few practical rules follow from this chapter:
- Check
s.isna().sum()right after loading, before any other conversion. - Remove placeholder categories at load time, not later.
- Add an explicit category only when "unknown" is an answer in its own right, as with a survey option "prefer not to say".
- Never use raw codes without handling
-1. - When you report counts or group totals, state whether missing rows are included.
Exercises
Exercise
A categorical column grade has categories ["A", "B", "?"], and the ? rows mean "not graded". You call df["grade"].value_counts() and see ? listed with a count. What single .cat call makes ? rows count as missing instead, and what happens to the categories?
Show answer
Call df["grade"] = df["grade"].cat.remove_categories("?"). Rows that held ? become NaN (code -1), and the categories become ["A", "B"]. After that, value_counts() skips those rows by default, and value_counts(dropna=False) shows them as a NaN row.
Exercise
Given s = pd.Series(["lo", None, "hi"], dtype=pd.CategoricalDtype(["lo", "hi"], ordered=True)), what does (s >= "hi").tolist() return, and how would you build a mask that selects rows that are "hi" or missing?
Show answer
It returns [False, False, True], because comparison with a missing value gives False. The mask s.isna() | (s >= "hi") selects the second and third rows and returns [False, True, True].
Exercise
You map codes to labels with labels[s.cat.codes] where labels is a NumPy array of three strings. One row of s is missing. Which label does that row get, and why is it a problem?
Show answer
It gets the last label in labels, because the missing code is -1 and NumPy indexes -1 from the end. No error is raised, so the wrong label appears silently. Guard against it with np.where(codes >= 0, labels[codes], "missing"), or use a pandas method such as map or cat.rename_categories that keeps the missing value as NaN.