Sub topic 3
Choosing your own bin edges
This chapter assumes you can create a pandas Series and know the basic pd.cut call from the previous chapter. You pass the bin edges yourself instead of asking pandas to split the range into equal widths.
Why pass explicit edges
Equal-width bins rarely match how people talk about data. Age groups, tax brackets, grade bands and price tiers all have boundaries that come from the domain. When you give pd.cut a list for bins, those values become the cut points.
Edges define the bins
A list of edges describes the boundaries between bins. N edges produce N - 1 bins, and each bin runs from one edge to the next.
Here is the full call:
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)By default each bin is closed on the right. The three bins are (0, 18], (18, 65] and (65, 120]. So 17 is a child, 25 and 42 are adults, and 67 and 90 are seniors. An age of exactly 18 would fall in the first bin, so it would count as a child. The next chapter covers how to change this.
Rules for the edges
pd.cut checks the list you give it:
- The edges must increase strictly.
[0, 65, 18, 120]raisesValueError: bins must increase monotonically.Repeated values are rejected for the same reason. - If you pass
labels, you need exactly one fewer label than edges. Four edges with four labels raises aValueError. - Edges can be floats, and they do not need to be evenly spaced.
Sort the edges yourself if they come from a config file or user input. Pandas does not sort them for you.
Leaving the ends open
Fixed outer edges are a common source of surprises. If one value is older than 120, it falls outside every bin and becomes NaN. Use infinity for the outer edges when the top or bottom of the range should have no limit.
import numpy as np
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90, 130])
bins = [-np.inf, 18, 65, np.inf]
labels = ["child", "adult", "senior"]
print(pd.cut(ages, bins=bins, labels=labels))Now 130 is a senior. The first bin is (-inf, 18], so any negative age would count as a child. If negative ages are invalid in your data, clean them before binning. Otherwise they will be silently labeled.
Using the bins afterward
The result is a categorical column, so you can use it directly as a group key. This example groups prices into bands you chose:
import pandas as pd
df = pd.DataFrame({"price": [5, 12, 18, 25, 40, 55, 70, 95]})
bins = [0, 20, 50, 100]
df["price_band"] = pd.cut(df["price"], bins=bins, labels=["low", "mid", "high"])
print(df.groupby("price_band", observed=True)["price"].agg(["count", "mean"]))The low band holds 5, 12 and 18, so its count is 3 and its mean is about 11.67. The mid band holds 25 and 40, and the high band holds 55, 70 and 95. Passing observed=True limits the output to bands that actually occur in the data.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Edges not in increasing order | `ValueError` | Sort the list first |
| Same number of labels as edges | `ValueError` | Use one label fewer than edges |
| Data below the first edge or above the last | `NaN` in the result | Widen the edges or use `-np.inf` and `np.inf` |
| Data exactly on the first edge | `NaN` with the default right-closed bins | Use `include_lowest=True` (next chapter) |
Exercise
You call pd.cut(pd.Series([0, 5, 10]), bins=[0, 5, 10], labels=["a", "b"]). Which values land in which bin, and which value, if any, becomes NaN?
Show answer
The bins are (0, 5] and (5, 10], because intervals are closed on the right by default. The value 5 gets "a" and 10 gets "b". The value 0 lies on the first edge, which is excluded, so it becomes NaN. Passing include_lowest=True would put 0 in "a".