Sub topic 3
Choosing your own bin edges
This chapter assumes you can create a pandas Series and a DataFrame, and that you know what a minimum, maximum and percentile are. You have already seen pd.cut split data into equal-width bins. Here you pass the edges yourself, which is the most common way pd.cut is used in real analysis.
Why set the edges yourself
Equal-width bins come from the data. If the largest value is an outlier, most rows land in the first bin and the result tells you little. Explicit edges come from your problem instead. Some examples:
- Age bands set by a business rule, such as under 18, 18 to 64 and 65 or older.
- Grade boundaries on a test score.
- Price tiers in a catalog.
- Clinical thresholds, such as blood pressure categories.
In each case the boundaries mean something outside the dataset. They should not change when new rows arrive, so you write them down.
The basic form
Pass a list of edges as the bins argument. The list defines the boundaries between bins, so the edges and the bins are counted differently:
| Edges in the list | Bins produced |
|---|---|
| 2 | 1 |
| 3 | 2 |
| 4 | 3 |
| n | n - 1 |
This one-off count is the source of most beginner mistakes. A list of four edges describes three bins, so a matching labels list has three entries.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
bins = [0, 18, 65, 120]
labels = ["child", "adult", "senior"]
groups = pd.cut(ages, bins=bins, labels=labels)
print(groups)The four edges create three intervals: 0 to 18, 18 to 65 and 65 to 120. Each interval is closed on the right by default. That means 18 belongs to the first interval and 65 belongs to the second. So 17 is a child, 25 and 42 are adult, and 67 and 90 are senior. The next chapter covers closure in detail. For now, remember that the left edge of the first bin is excluded.
Rules for the edge list
pd.cut checks the edges before it does any work. Keep these rules in mind:
- Edges must increase. An unsorted list such as
[0, 65, 18, 120]raises aValueError. Pandas does not sort the list for you. - Edges must be unique. A repeated edge would create a bin of zero width, so pandas raises a
ValueError. - Labels must match the bin count. Passing the wrong number of labels raises a
ValueError. - Edges can be integers or floats. Mixing the two is fine. Use floats when your boundaries are fractional, such as
[0, 0.5, 1.0].
You can see the failures directly:
import pandas as pd
ages = pd.Series([3, 17, 25])
try:
pd.cut(ages, bins=[0, 65, 18, 120])
except ValueError as err:
print("unsorted edges:", err)
try:
pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult"])
except ValueError as err:
print("wrong label count:", err)Both errors name the problem. If you build the edge list from a variable, sort it first with sorted(...). This is cheap and avoids the first error entirely.
Open-ended first and last bins
A fixed upper edge such as 120 is a guess. If a value of 130 appears, it falls outside every bin and becomes NaN. For quantities that have no natural maximum, use infinity for the outer edges. NumPy provides np.inf:
import numpy as np
import pandas as pd
amounts = pd.Series([-5, 0, 3, 50, 1000])
bins = [-np.inf, 0, 10, 100, np.inf]
labels = ["zero or negative", "small", "medium", "large"]
print(pd.cut(amounts, bins=bins, labels=labels))Every number now lands in some bin. The values -5 and 0 fall in the first bin because it is closed on the right at 0. The values 3, 50 and 1000 land in small, medium and large. This also removes the leftmost-edge problem, because nothing sits exactly at negative infinity.
Open-ended bins work well for the extremes of skewed data, such as income or file sizes. They have one cost. Intervals with an infinite end have no meaningful width, so you cannot compute a midpoint for them. If you plan to use interval midpoints later, close the bins with real limits.
Choosing the edges
There are three common ways to pick the numbers, and they differ in how well they hold up:
| Source of edges | Example | Strength | Risk |
|---|---|---|---|
| Domain rule | Age 18 and 65 | Stable and easy to explain | None, if the rule is real |
| Round numbers near the data | 0, 25, 50, 75, 100 | Readable bin names | May leave some bins nearly empty |
| Computed from the data | Min and max padded slightly | Covers the current data | Changes with each new dataset |
If you compute edges from the data, remember that the minimum is not covered by a right-closed first bin. A small pad avoids this:
import pandas as pd
scores = pd.Series([12.5, 40.0, 55.5, 71.0, 88.5, 97.0])
low = scores.min() - 1
high = scores.max() + 1
edges = [low, 50, 75, high]
print(edges)
print(pd.cut(scores, bins=edges, labels=["low", "middle", "high"]))The edges are [11.5, 50, 75, 98.0]. The lowest score, 12.5, sits above 11.5, so it is included. A padded edge is a reasonable choice for a one-off analysis. For a pipeline that runs repeatedly on new data, prefer np.inf or fixed limits, so the result does not depend on the batch.
Checking the result
Binning errors are silent. A wrong edge does not raise an error. It just moves rows into the wrong bin. Two quick checks catch most problems.
First, count the missing values after binning. Any NaN that was not in the input means some values fell outside your edges:
import pandas as pd
ages = pd.Series([0, 3, 17, 25, 130])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.isna().sum())
print(ages[groups.isna()])This prints a count of 2 and the offending values, 0 and 130. The 0 sits on the excluded left edge, and the 130 is above the last edge. Fixing the first needs the closure options from the next chapter. Fixing the second needs a higher last edge or np.inf.
Second, look at how many rows each bin holds. You can use value_counts with sort=False to keep the bins in their natural order:
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts(sort=False))Here the three bins hold 2, 2 and 2 rows. A bin with zero rows is not an error, but it can mean an edge is misplaced. Bins with zero rows still appear in the output because the result is a categorical type, which keeps every category.
Common errors
- Counting edges as bins. Four edges give three bins. Pass three labels, not four.
- Forgetting the left edge. With the default settings, a value equal to the first edge becomes
NaN. A common case is a minimum of 0 withbins=[0, ...]. - Assuming the edges are sorted. Pandas will not do it for you.
- Hard-coding a maximum. A last edge of 100 fails when a 101 arrives. Use
np.infwhere there is no true limit. - Reading the bins as inclusive on both sides. Each interval has one closed side and one open side. Check which one before you decide where a boundary value goes.
Summary
Explicit edges give you bins with a meaning you choose. A list of n edges creates n - 1 bins, so the label list must have n - 1 entries. The list must be sorted and have no repeats. Use np.inf when a bin should have no upper or lower limit. Check the result for new NaN values and for empty bins before you use it.
Exercise
You run pd.cut(pd.Series([0, 18, 19, 65]), bins=[0, 18, 65, 120], labels=["child", "adult", "senior"]) with the default settings. Which value becomes NaN, and what label does each of the other values receive?
Show answer
Only 0 becomes NaN, because the first interval (0, 18] is closed on the right and excludes its left edge. The value 18 is labeled "child", 19 is labeled "adult", and 65 is labeled "adult" because (18, 65] includes 65.
Exercise
A colleague writes pd.cut(x, bins=[0, 10, 20, 30, 40], labels=["a", "b", "c", "d", "e"]). What happens, and how do you fix it?
Show answer
Pandas raises a ValueError, because five edges make four bins and five labels do not match. Remove one label to leave four, or add one more edge if you want five bins.