Sub topic 12
Turning numbers into categories with cut and qcut
Binning converts a numeric column into labeled ranges such as "low", "mid", and "high". This chapter covers pd.cut, which uses edges you choose, and pd.qcut, which picks edges so each bin holds about the same number of rows. It assumes you can create a DataFrame, select a column by name, and assign a new column with df["name"] = .... Earlier chapters covered np.select, which also builds categories. Here you will see when binning is the better tool.
What binning produces
Both functions take a numeric Series and return a Series of dtype category. Each value is replaced by the bin it falls into. The result is a new column, so you assign it like any other derived column. Because the dtype is categorical, the bins have a fixed set of labels and a defined order. That affects sorting, counting, and grouping, as the later sections show.
Fixed edges with pd.cut
Pass the edges as a list. With n edges you get n − 1 bins.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp", "desk", "mug"],
"price": [1.5, 12.0, 30.0, 5.0, 0.0],
})
df["price_band"] = pd.cut(
df["price"],
bins=[0, 5, 20, float("inf")],
labels=["low", "mid", "high"],
)
print(df)The edges define the intervals (0, 5], (5, 20], and (20, inf]. Each interval is open on the left and closed on the right. Two rows show what that means:
deskcosts exactly 5.0, so it lands in "low", because 5 is the right edge of the first bin.mugcosts 0.0, so it getsNaN, because 0 is the left edge of the first bin and the left edge is excluded.
Without labels, cut uses the interval itself as the label, for example (0.0, 5.0]. That is useful for checking your edges before you name the bins.
Controlling which side is closed
Two arguments change the edge behavior:
right=Falsemakes the intervals closed on the left and open on the right: [0, 5), [5, 20), [20, inf).include_lowest=Truemakes the first interval include its left edge. Use it with the defaultright=Trueto catch the minimum value.
closed_left = pd.cut(
df["price"], bins=[0, 5, 20, float("inf")],
labels=["low", "mid", "high"], right=False,
)
with_zero = pd.cut(
df["price"], bins=[0, 5, 20, float("inf")],
labels=["low", "mid", "high"], include_lowest=True,
)
print(pd.DataFrame({"price": df["price"], "closed_left": closed_left, "with_zero": with_zero}))With right=False, the 5.0 moves from "low" to "mid", and 0.0 becomes "low". With include_lowest=True, 5.0 stays "low" and 0.0 also becomes "low". Pick the convention that matches your business rule, then write it down. Off-by-one-edge mistakes in binning are common and hard to see in the output.
Values outside the edges become NaN
Any value below the first edge or above the last edge gets NaN. This is silent, with no warning. Use -float("inf") and float("inf") as outer edges when you want every value covered. Alternatively, count the missing results after binning:
print(df["price_band"].isna().sum())If that count is higher than the number of missing prices you started with, your edges leave gaps.
Equal-width bins
If you pass an integer instead of a list, cut splits the range from the minimum to the maximum into that many bins of equal width.
prices = pd.Series([1.5, 12.0, 30.0, 5.0, 0.0, 8.0, 22.0])
print(pd.cut(prices, bins=3))cut extends the outer edges slightly (by 0.1% of the range) so that the minimum and maximum fall inside. The printed edges therefore look a little odd. Equal-width bins are sensitive to outliers. One very large value stretches the range, and most rows end up in the first bin.
Equal-count bins with pd.qcut
qcut chooses edges from the data's quantiles, so each bin holds about the same number of rows. Pass q=4 for quartiles, q=10 for deciles, or a list of quantile fractions such as [0, 0.5, 0.9, 1].
scores = pd.Series([52, 61, 67, 70, 74, 78, 83, 88])
quartile = pd.qcut(scores, q=4, labels=["Q1", "Q2", "Q3", "Q4"])
print(pd.DataFrame({"score": scores, "quartile": quartile}))
print(quartile.value_counts().sort_index())Here the eight scores split into four bins of two rows each. The edges (52, 65.5, 72, 79.25, 88) come from the data, so a different dataset gives different edges. This makes qcut good for ranking ("top 10%") and bad for fixed business thresholds ("under $20").
Repeated values and duplicate edges
When one value is very common, several quantiles can be identical. The edges are then not unique, and qcut raises a ValueError saying the bin edges must be unique. The fix is duplicates="drop", which removes the repeated edges and gives you fewer bins than you asked for.
visits = pd.Series([0, 0, 0, 0, 0, 1, 5, 9])
bins = pd.qcut(visits, q=4, labels=False, duplicates="drop")
print(bins.nunique())Because the number of bins is no longer known in advance, a list of four labels would fail here. Use labels=False to get integer bin numbers, or build the labels after you see how many bins you got.
Working with the categorical result
The output dtype is category, so a few behaviors differ from a plain string column.
- Order is kept.
cutandqcutreturn ordered categoricals.value_counts()sorts by frequency, so call.sort_index()to see the bins in their natural order. - Empty bins are kept. A bin with no rows still appears in
value_counts()with a count of 0. Ingroupby, setobserved=Trueorobserved=Falseexplicitly. The default has changed between pandas versions, and an explicit value keeps the output stable. - Missing values stay missing. A
NaNin the input givesNaNin the output. It is not placed in any bin. - Converting to text can mislead.
astype(str)turnsNaNinto the string"nan", which then looks like a real label. Useastype("object")if you need a non-categorical column and want to keep the missing values.
print(df.groupby("price_band", observed=True)["price"].mean())
df["price_band"] = (
df["price_band"].cat.add_categories("unknown").fillna("unknown")
)
print(df["price_band"].value_counts().sort_index())You must add the new label with add_categories before fillna can use it. Filling with a label that is not an existing category raises an error.
Choosing between cut, qcut, and np.select
Use cut when the thresholds come from a rule you can state. Use qcut when the thresholds should follow the data. Use np.select when the rule depends on more than one column or on conditions that are not simple ranges. cut is also shorter than the equivalent np.select call, and it returns an ordered categorical, which np.select does not.
Summary of arguments
| Argument | Applies to | Effect |
|---|---|---|
| `bins` / `q` | `cut` / `qcut` | Edges or count (`cut`), quantile count or fractions (`qcut`) |
| `labels` | both | Names for the bins, or `False` for integer codes |
| `right` | `cut` | `True` (default) closes the right edge; `False` closes the left |
| `include_lowest` | `cut` | Includes the first left edge when `right=True` |
| `duplicates` | `qcut` (also `cut`) | `"drop"` removes repeated edges instead of raising |
| `ordered` | both | Keeps the categories in order (default `True`) |
Exercise
A Series ages = pd.Series([4, 17, 18, 35, 64, 65, 90]) must be binned into "minor" (under 18), "adult" (18 to 64), and "senior" (65 and over). Write the pd.cut call, and say which arguments make 18 and 65 land in the right bins.
Show answer
Use right=False so each interval includes its left edge: pd.cut(ages, bins=[0, 18, 65, float("inf")], labels=["minor", "adult", "senior"], right=False). The intervals are [0, 18), [18, 65), and [65, inf), so 18 is "adult" and 65 is "senior". With the default right=True, 18 would be "minor" and 65 would be "adult", which breaks the rule. The lowest edge 0 is included because right=False closes the left side, so 4 is "minor".