Sub topic 7
NaN results: out-of-range and missing values
This chapter assumes you can call pd.cut and pd.qcut with explicit edges, and that you know what right=True and include_lowest do. It also assumes you can build a Series or DataFrame and filter it with a boolean mask. Here you learn why binning produces NaN, how to tell the causes apart, and how to fix each one.
Three sources of NaN
A binned result can contain NaN for three different reasons. They need different fixes, so diagnose before you patch.
- The value is outside every bin. It is below the first edge or above the last edge.
- The value sits on an excluded edge. With the default
right=True, the first interval is open on the left, so a value equal to the first edge belongs to no interval. Withright=False, the same thing happens to a value equal to the last edge. - The input was already missing.
NaNgoes in, andNaNcomes out. Binning never invents or fills a category for a missing value.
The first two are caused by your bin edges. The third is a property of your data.
Seeing all three in one example
The Series below contains one value from each cause. It has -1 (below the range), 0 (on the excluded left edge), 130 (above the range) and a real NaN.
import numpy as np
import pandas as pd
ages = pd.Series([-1, 0, 5, 18, 70, 130, np.nan])
bins = [0, 18, 65, 120]
labels = ["child", "adult", "senior"]
groups = pd.cut(ages, bins=bins, labels=labels)
print(groups.isna().sum())This prints 4. Only 5, 18 and 70 received a label (child, child and senior). Four of the seven results are NaN, but only one of them was missing in the input.
Count the input NaN separately from the unbinned values:
import numpy as np
import pandas as pd
ages = pd.Series([-1, 0, 5, 18, 70, 130, np.nan])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
was_missing = ages.isna()
lost_in_binning = groups.isna() & ages.notna()
print("missing in input:", int(was_missing.sum()))
print("lost by the bins:", ages[lost_in_binning].tolist())The output is:
missing in input: 1
lost by the bins: [-1.0, 0.0, 130.0]The mask groups.isna() & ages.notna() is the key expression. It selects rows where the input had a value but the result did not. Those rows point to a problem with your edges, or to bad data.
A diagnostic path
The diagram summarizes how to decide what to do with each NaN in the output.
Fixing values on an excluded edge
The value 0 failed because the first interval is (0, 18]. Setting include_lowest=True turns the first interval into [0, 18].
import pandas as pd
ages = pd.Series([0, 5, 18])
groups = pd.cut(ages, bins=[0, 18, 65, 120],
labels=["child", "adult", "senior"],
include_lowest=True)
print(groups.tolist())This prints ['child', 'child', 'child']. The parameter affects only the first interval. If the problem is a value equal to the last edge (possible with right=False), include_lowest will not help. Move the last edge above the largest value you expect.
Fixing values beyond the outer edges
Values outside the outer edges have two possible fixes. Choose based on whether the value is legitimate.
If the value is legitimate but outside your planned range, widen the bins. Infinite edges are accepted by pd.cut and give you open-ended top and bottom bins:
import numpy as np
import pandas as pd
ages = pd.Series([5, 18, 70, 130])
groups = pd.cut(ages, bins=[-np.inf, 18, 65, np.inf],
labels=["child", "adult", "senior"])
print(groups.tolist())This prints ['child', 'child', 'senior', 'senior']. The age 130 is now counted as senior.
If the value is not legitimate, widening the bins hides a data problem. An age of -1 is probably an error. Putting it in the "child" bin through -inf would silently mix bad data into a valid group. Here the NaN is useful, because it flags a row that deserves attention.
Failing loudly instead of silently
A pipeline that bins data often runs unattended. A small check turns a silent NaN into an explicit error:
import numpy as np
import pandas as pd
def cut_strict(values, bins, labels):
"""Bin values and raise if any non-missing value falls outside the bins."""
result = pd.cut(values, bins=bins, labels=labels, include_lowest=True)
outside = values[result.isna() & values.notna()]
if not outside.empty:
raise ValueError(f"Values outside the bins: {outside.tolist()}")
return result
ages = pd.Series([3, 40, 130, np.nan])
try:
cut_strict(ages, [0, 18, 65, 120], ["child", "adult", "senior"])
except ValueError as err:
print(err)This prints Values outside the bins: [130.0]. The real NaN in the input does not trigger the error, because the check ignores rows where the input was already missing.
Missing input
Missing values stay missing. Three common treatments exist:
- Drop them before binning with
dropna(), if the rows are not needed. - Keep them as NaN and count them explicitly in summaries.
- Give them a category so they appear in group-by output.
The third option needs one extra step. A categorical column accepts only values from its list of categories, so you must add the new category before filling:
import numpy as np
import pandas as pd
ages = pd.Series([5, 40, np.nan])
groups = pd.cut(ages, bins=[0, 18, 65, 120],
labels=["child", "adult", "senior"])
labeled = groups.cat.add_categories("unknown").fillna("unknown")
print(labeled.tolist())This prints ['child', 'adult', 'unknown']. Calling fillna("unknown") without add_categories first raises an error, because "unknown" is not an existing category.
What qcut does differently
pd.qcut computes its edges from the data, using the minimum as the lowest edge and the maximum as the highest. Every non-missing value therefore falls inside some bin. Cases 1 and 2 above cannot happen with qcut unless you pass quantile fractions that do not span the full range, such as [0.1, 0.5, 0.9]. Fractions like that leave the lowest 10% and the highest 10% unbinned.
Missing input still produces NaN. The quantiles are computed from the non-missing values only:
import numpy as np
import pandas as pd
scores = pd.Series([10, 20, 30, 40, np.nan, 60, 70, 80])
halves = pd.qcut(scores, q=2, labels=["low", "high"])
print(int(halves.isna().sum()))
print(halves.value_counts())The first line prints 1. The median of the seven present values is 40, so 10, 20, 30 and 40 are low, and 60, 70 and 80 are high. The missing score is excluded from the counts.
NaN in summaries
Binned NaN values disappear from most summaries by default, which can make totals look smaller than the original data.
value_counts()skipsNaN. Passdropna=Falseto include aNaNrow in the counts.groupbydrops rows whose key isNaN. Passdropna=Falseto keep them as their own group. Behavior with categorical keys has changed across pandas versions, so confirm it on the version you use.
import numpy as np
import pandas as pd
ages = pd.Series([-1, 0, 5, 18, 70, 130, np.nan])
groups = pd.cut(ages, bins=[0, 18, 65, 120],
labels=["child", "adult", "senior"])
print(groups.value_counts().sum())
print(groups.value_counts(dropna=False).sum())The first line prints 3 and the second prints 7. A quick way to detect lost rows is to compare the sum of the counts with len(ages).
Summary of causes and fixes
| Cause | Applies to | Typical fix |
|---|---|---|
| Value below first edge or above last edge | `cut`, `qcut` with partial fractions | Widen edges, or clean the data |
| Value equals first edge with `right=True` | `cut` | `include_lowest=True` |
| Value equals last edge with `right=False` | `cut` | Move the last edge higher |
| Input value is `NaN` | `cut`, `qcut` | Drop, keep, or add a category |
Exercise
You run pd.cut(pd.Series([0, 50, 100, 150]), bins=[0, 100], labels=["all"]) and get two NaN values. Which values are they, why, and what is the smallest change that makes 0 and 100 land in the bin without accepting 150?
Show answer
The NaN values are 0 and 150. The only interval is (0, 100], so 0 is excluded because the interval is open on the left, and 150 is above the last edge. Add include_lowest=True, which makes the interval [0, 100]. Value 100 was already included, and 150 stays NaN, which is the intended result.
Exercise
A pipeline bins customer ages with pd.cut and then runs groupby on the result with default settings. The group counts add up to 9,640, but the table has 10,000 rows. Name two possible causes and one expression that separates them.
Show answer
Some rows had a missing age, or some ages fell outside the bin edges. Both leave NaN keys, and groupby drops NaN keys by default. The expression groups.isna() & ages.notna() is True only for rows lost by the bins, while ages.isna() marks rows that were missing in the input.