Sub topic 7
NaN results: out-of-range and missing values
This chapter assumes you can build a Series, call pd.cut with explicit edges, and read interval notation such as (0, 18]. Binning functions never raise an error when a value has no bin. They return NaN for that value. This chapter shows how to find those NaN values, tell their causes apart, and fix them.
Where the NaN values come from
A binned value is NaN for one of three reasons:
- The value is below the first edge or above the last edge.
- The value sits exactly on an open edge. With the default
right=True, the first interval is(0, 18], so a value of0is excluded. - The input was already missing.
The example below triggers all three.
import pandas as pd
ages = pd.Series([-1, 0, 18, 70, 130, None])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(pd.DataFrame({"age": ages, "group": groups}))The output shows NaN for -1 (below the range), 0 (on the open lower edge), 130 (above the range) and the missing input. Only 18 and 70 receive labels.
Separating bad bins from missing input
All three causes look the same in the result, so compare the output with the input. A value that is missing in the output but present in the input fell outside the bins.
fell_outside = groups.isna() & ages.notna()
print(ages[fell_outside])This prints -1, 0 and 130. The missing input is not listed, because it was already NaN.
Fixing the cases
For values above the top edge, extend the last edge to infinity. Use include_lowest=True so that 0 falls in the first bin.
import pandas as pd
ages = pd.Series([-1, 0, 18, 70, 130, None])
groups = pd.cut(
ages,
bins=[0, 18, 65, float("inf")],
labels=["child", "adult", "senior"],
include_lowest=True,
)
print(groups)Now 0 is a child and 130 is a senior. The -1 stays NaN, which is the right outcome if a negative age is a data error. Leaving such values as NaN flags them. Widening the edges to -inf would hide them.
For missing input, cut has nothing to assign, so it keeps NaN. If you want an explicit group, add a category and fill with it.
groups = groups.cat.add_categories("unknown").fillna("unknown")
print(groups.value_counts())Adding the category first is required. The result is categorical, and fillna on a categorical column rejects a value that is not already a category.
What about qcut?
pd.qcut builds its edges from the data, and the lowest and highest edges are the minimum and maximum. Every value from the input therefore lands in a bin. Missing input is ignored when the quantiles are computed, and it stays NaN in the result. Out-of-range NaN values are mainly a pd.cut concern, because there you choose the edges.
Quick reference
| Cause | Sign | Fix |
|---|---|---|
| Value beyond the edges | Present in input, `NaN` in output | Widen edges, for example with `float("inf")` |
| Value on the open lowest edge | Equals the first edge | `include_lowest=True` |
| Value on an open edge with `right=False` | Equals the last edge | Add a larger final edge |
| Missing input | `NaN` in input | `add_categories` then `fillna`, or clean the input first |
Exercise
You run pd.cut(pd.Series([5, 10, 20]), bins=[5, 10, 20]) and get NaN for the first value. Why does it happen, and how do you keep 5 in the first bin without changing the edges?
Show answer
The default right=True makes the first interval (5, 10], which excludes 5. Passing include_lowest=True makes the first interval [5, 10], so 5 is included.