Sub topic 14
Reusing bins with an IntervalIndex
This chapter assumes you know pd.cut and pd.qcut, the right and include_lowest parameters, and the categorical result that binning returns. It shows how to build the bins once and apply them to more than one dataset.
Why reuse bins
Suppose you bin a training set with pd.qcut. Later, new data arrives. Calling qcut again on the new data computes new quantiles, so the same value can land in a different bin. You need the bin definitions to stay fixed.
An IntervalIndex is a pandas index whose items are intervals. Passing one as bins tells cut to use those exact intervals.
Building an IntervalIndex
pd.IntervalIndex.from_breaks takes a list of edges and joins neighbouring edges into intervals. It is closed on the right unless you pass closed.
import pandas as pd
bins = pd.IntervalIndex.from_breaks([0, 18, 65, 120])
print(bins)
new_ages = pd.Series([0, 18, 19, 130])
print(pd.cut(new_ages, bins))The index holds (0, 18], (18, 65] and (65, 120]. The result for new_ages follows these rules:
- 0 is
NaN, because the interval(0, 18]excludes 0. - 18 falls in
(0, 18]. - 19 falls in
(18, 65]. - 130 is
NaN, because it is above the last edge.
For other layouts, use from_tuples or from_arrays.
What changes when bins is an IntervalIndex
- Closure comes from the index. The
rightandinclude_lowestarguments are ignored. To get left-closed bins, build the index withclosed="left". - The
labelsargument is ignored. The intervals themselves are the categories. - The intervals must not overlap. Overlapping intervals raise a
ValueError. - The intervals may have gaps. A value that falls in a gap becomes
NaN.
gappy = pd.IntervalIndex.from_tuples([(0, 10), (20, 30)])
print(pd.cut(pd.Series([5, 15, 25]), gappy))Here 15 sits between the two intervals, so it becomes NaN.
Freezing qcut bins for new data
qcut with retbins=True returns the edges it computed. You can turn those edges into an IntervalIndex and apply them to later data.
One detail needs care. qcut includes the lowest value in the first bin, but a right-closed IntervalIndex does not. If you build the index from the raw edges, a new value at or below the training minimum becomes NaN. Replace the outer edges with minus and plus infinity so that any new value is covered.
import numpy as np
import pandas as pd
train = pd.Series([4, 8, 15, 16, 23, 42, 57, 61])
_, edges = pd.qcut(train, q=4, retbins=True)
breaks = [-np.inf, *edges[1:-1], np.inf]
bins = pd.IntervalIndex.from_breaks(breaks)
print(bins)
new = pd.Series([1, 20, 50, 500])
print(pd.cut(new, bins))The inner edges are the training quartiles: 13.25, 19.5 and 45.75. The value 1 lands in the first bin, 20 in the third, and both 50 and 500 in the last.
Checking the result
The categories of the result are the intervals you passed in. You can confirm this with result.cat.categories. Because every interval stays in the categories, even empty ones, value_counts() shows zero counts for bins that no value fell into. This keeps the output the same shape across datasets.
Exercise
You build bins = pd.IntervalIndex.from_breaks([0, 10, 20]) and call pd.cut(pd.Series([0, 10, 20]), bins, include_lowest=True). Which values become NaN, and why?
Show answer
Only 0 becomes NaN. With an IntervalIndex, include_lowest is ignored, and the intervals (0, 10] and (10, 20] are closed on the right and exclude 0. The values 10 and 20 fall in (0, 10] and (10, 20]. To keep 0, build the index with a lower first edge such as -1, or use closed="both" on non-overlapping intervals only if they do not overlap.