Sub topic 14
Reusing Bins with an IntervalIndex
This chapter assumes you know pd.cut and pd.qcut from the earlier chapters, including explicit edges, interval closure and the categorical result. It also assumes you can build a Series and a DataFrame. Here you will learn to define bins once as an IntervalIndex and apply them to any number of datasets.
Why reuse bins
When you pass a list of edges to pd.cut, pandas builds the intervals on every call. That works for a single analysis. It becomes a problem in three common situations:
- You bin a training set and later need the same bins for new data.
- Two DataFrames, such as this month's and last month's orders, must be comparable band by band.
- The bins come from a business rule, such as age bands or tax brackets, and should live in one place in your code.
pd.qcut makes the first case acute. Its edges are computed from the data, so calling qcut on new data produces different edges. Counts per bin then mean different things in each dataset.
An IntervalIndex is a pandas index whose entries are intervals. If you pass one as bins, pd.cut uses those exact intervals without recomputing anything.
Building an IntervalIndex
There are three common constructors:
| Constructor | Input | Use when |
|---|---|---|
| `IntervalIndex.from_breaks` | A list of edges | The bins are contiguous |
| `IntervalIndex.from_tuples` | A list of `(left, right)` pairs | Bins have gaps between them |
| `IntervalIndex.from_arrays` | Two lists, lefts and rights | Your bounds are already in two columns |
Contiguous bins are the usual case:
import pandas as pd
intervals = pd.IntervalIndex.from_breaks([0, 18, 65, 120])
print(intervals)
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups = pd.cut(ages, bins=intervals)
print(groups)from_breaks([0, 18, 65, 120]) produces the intervals (0, 18], (18, 65] and (65, 120]. They are closed on the right, which is the same default as pd.cut. The result matches pd.cut(ages, bins=[0, 18, 65, 120]). The difference is that you now hold the bins as an object you can store and pass around.
Applying the same bins to new data
Because the intervals are fixed, new data lands in the same bins as the original. Values outside every interval become NaN:
import pandas as pd
intervals = pd.IntervalIndex.from_breaks([0, 18, 65, 120])
january = pd.Series([3, 17, 25, 42, 67, 90])
february = pd.Series([0, 18, 70, 130])
print(pd.cut(january, bins=intervals).value_counts().sort_index())
print(pd.cut(february, bins=intervals))In february, the value 0 is not in (0, 18] because the left edge is open. The value 130 lies beyond the last edge. Both give NaN. The value 18 is in (0, 18] because the right edge is closed.
Both results share the same categories, so the two value_counts outputs line up row for row.
What changes when bins is an IntervalIndex
Several pd.cut parameters behave differently once bins is an IntervalIndex:
rightis ignored. The closure comes from the index itself.include_lowestis ignored for the same reason.labelsis ignored. The categories are always the intervals.- Overlapping intervals raise
ValueError. Each value must map to at most one bin.
The closure is chosen when you build the index, with the closed argument:
import pandas as pd
left_closed = pd.IntervalIndex.from_breaks([0, 10, 20], closed="left")
values = pd.Series([0, 10, 20])
print(pd.cut(values, bins=left_closed))The intervals are [0, 10) and [10, 20). The value 0 is now included, 10 falls in the second interval, and 20 becomes NaN. The valid options for closed are "left", "right", "both" and "neither".
Labels with an IntervalIndex
Since labels is ignored, rename the categories after cutting:
import pandas as pd
intervals = pd.IntervalIndex.from_breaks([0, 18, 65, 120])
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups = pd.cut(ages, bins=intervals, labels=["child", "adult", "senior"])
print(groups.cat.categories)
groups = groups.cat.rename_categories(["child", "adult", "senior"])
print(groups.tolist())The first print still shows intervals, which confirms the labels argument had no effect. After rename_categories, the column holds the readable names. Keep the list of names next to the IntervalIndex definition so the two stay in the same order.
If you need labels on every call, plain pd.cut(ages, bins=[0, 18, 65, 120], labels=[...]) with a stored list of edges is often simpler. Use an IntervalIndex when you need its extra features: gaps between bins, mixed closure, or categories taken from another result.
Bins with gaps
from_breaks always produces contiguous intervals. from_tuples lets you leave gaps. Values in a gap map to NaN, which is useful when some ranges are not valid:
import pandas as pd
valid_ranges = pd.IntervalIndex.from_tuples([(0, 10), (20, 30)])
readings = pd.Series([5, 15, 25])
print(pd.cut(readings, bins=valid_ranges))The reading 15 is in the gap between the two intervals, so it becomes NaN. You can use that NaN as a marker for out-of-range data. Adding .isna() to the result gives a quick check for readings that fall outside every allowed range.
Reusing qcut edges
The most useful application is freezing qcut bins. A fitted qcut result is a categorical whose categories are already an IntervalIndex. Read them from .cat.categories and pass them to pd.cut:
import pandas as pd
train = pd.Series(range(1, 101))
train_bins = pd.qcut(train, q=4)
fitted = train_bins.cat.categories
print(fitted)
new_data = pd.Series([5, 30, 80, 150, -3])
print(pd.cut(new_data, bins=fitted))The four fitted intervals are about (0.999, 25.75], (25.75, 50.5], (50.5, 75.25] and (75.25, 100.0]. The value 5 falls in the first and 30 in the second. The value 80 falls in the last. The values 150 and -3 lie outside the training range, so they become NaN.
The lowest edge is 0.999 rather than 1. qcut lowers the first edge slightly so the minimum value is included. Reusing those categories keeps that adjustment, so a new value equal to the training minimum still lands in the first bin.
Handling values beyond the training range
New data often contains values larger or smaller than anything in the training set. To avoid NaN for these, extend the outer edges to infinity:
import numpy as np
import pandas as pd
train = pd.Series(range(1, 101))
_, edges = pd.qcut(train, q=4, retbins=True)
edges[0] = -np.inf
edges[-1] = np.inf
open_bins = pd.IntervalIndex.from_breaks(edges)
new_data = pd.Series([5, 30, 80, 150, -3])
print(pd.cut(new_data, bins=open_bins))This gives four bins: (-inf, 25.75], (25.75, 50.5], (50.5, 75.25] and (75.25, inf]. Every number now has a bin, so 150 is in the top bin and -3 in the bottom one. The trade-off is that the outer bins no longer describe a bounded range. Check whether a flood of extreme values should be a data quality alert instead of being folded into an edge bin.
Consistent summaries across datasets
Because every pd.cut call with the same IntervalIndex produces the same categories, summaries have the same rows even when a band is empty in one dataset:
import pandas as pd
intervals = pd.IntervalIndex.from_breaks([0, 20, 50, 100])
jan = pd.DataFrame({"price": [5, 12, 18, 25, 40]})
feb = pd.DataFrame({"price": [55, 70, 95]})
for name, df in [("jan", jan), ("feb", feb)]:
df["band"] = pd.cut(df["price"], bins=intervals)
print(name)
print(df.groupby("band", observed=False)["price"].agg(["count", "mean"]))With observed=False, February still lists the (0, 20] and (20, 50] bands, with a count of zero and a mean of NaN. Setting observed=True would drop those rows and make the two tables harder to compare. For stable reports, prefer observed=False.
Common mistakes
- Passing overlapping intervals.
from_tuples([(0, 10), (5, 15)])is a validIntervalIndex, butpd.cutraisesValueErrorfor it. Fix the bounds so each value belongs to one bin. - Expecting
labelsto work. It is silently ignored. Rename the categories after cutting. - Mixing up closure. A default
from_breaksis right-closed. If your rules say "18 and older is an adult", build the index withclosed="left". - Rerunning
qcuton new data. This computes fresh edges. Freeze the training edges and usepd.cut. - Forgetting the lowest value. With right-closed intervals, a value equal to the first edge is excluded unless you built the intervals to include it, for example by lowering the first edge or using
closed="both".
Exercise
You fit pd.qcut(train, q=5) on last year's salaries and now need to bin this year's salaries into the same five groups, with no NaN values for unusually high or low salaries. Which steps do you take?
Show answer
Call pd.qcut(train, q=5, retbins=True) to get the edges. Replace the first edge with -np.inf and the last edge with np.inf. Build pd.IntervalIndex.from_breaks(edges) and pass it as bins to pd.cut(this_year, bins=...). Every salary now falls in one of the five bins, and the inner edges are the same as last year's.
Exercise
A colleague writes pd.cut(values, bins=pd.IntervalIndex.from_breaks([0, 10, 20]), right=False) and expects intervals like [0, 10). Why is the result wrong, and how do you fix it?
Show answer
right is ignored when bins is an IntervalIndex, so the intervals stay (0, 10] and (10, 20]. Set the closure when you build the index: pd.IntervalIndex.from_breaks([0, 10, 20], closed="left").