Sub topic 8
Turning numbers into categories with cut and qcut
This chapter assumes you can build a pandas Series, know the category dtype (categories plus integer codes), and have read the earlier chapters on ordered categoricals. Here you will turn continuous numbers such as ages, prices, or scores into labeled groups. You will see the two main tools, pd.cut and pd.qcut, and the edge cases that commonly produce wrong results.
Why bin numbers at all
Binning replaces a numeric column with a small set of ordered groups. Typical reasons:
- Reporting. "Customers by age group" is easier to read than a table of 80 distinct ages.
- Grouping. A binned column can be a
groupbykey or a pivot axis. - Reducing noise. Exact values are less meaningful than the range they fall in.
- Feature engineering. Some models and rules work with ranges.
Binning discards information, so do it only when the groups mean something. Both functions return a categorical Series, so everything from earlier chapters applies to the result: .cat.categories, .cat.codes, and memory savings.
Choosing between cut and qcut
The two functions differ in how they decide where the bin edges go.
pd.cutuses edges you choose, or equal-width bins across the data range. The bins have meaning in your domain, but the number of rows in each bin can be very uneven.pd.qcutuses quantiles of the data, so each bin gets roughly the same number of rows. The bin widths vary, and the edges are whatever the data produces.
pd.cut with explicit edges
Pass a list of edges as bins. N edges define N-1 bins, so labels must have exactly N-1 entries.
import pandas as pd
ages = pd.Series([5, 17, 30, 64, 80])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.tolist()) # ['child', 'child', 'adult', 'adult', 'senior']
print(groups.dtype)
print(groups.dtype.ordered) # TrueThree details matter here:
- By default each bin is right-inclusive:
(0, 18]excludes 0 and includes 18. So 18 is a child and 19 is an adult. - The result is an ordered categorical by default (pandas 1.1 and later), so
groups >= "adult"andgroups.max()work with no extra setup. Passordered=Falseif the labels have no natural order.ordered=Falseis only allowed when you give explicit labels. - If you omit
labels, the categories areIntervalobjects such as(0, 18]. That is useful for exploration, but labels are better in output that other people will read.
Boundaries and the include_lowest trap
A value outside every bin becomes NaN. The common surprise is a value that sits exactly on the lowest edge. With right-inclusive bins, the lowest edge is excluded.
import pandas as pd
x = pd.Series([0, 10, 20])
default = pd.cut(x, bins=[0, 10, 20], labels=["low", "high"])
fixed = pd.cut(x, bins=[0, 10, 20], labels=["low", "high"], include_lowest=True)
print(default.tolist()) # [nan, 'low', 'high']
print(fixed.tolist()) # ['low', 'low', 'high']The zero was silently dropped in the first call. These parameters control the edges:
| Parameter | Effect |
|---|---|
| `right=True` (default) | Bins are `(a, b]`. Set `right=False` for `[a, b)`. |
| `include_lowest=True` | Also includes the first edge in the first bin (with `right=False`, it includes the last edge in the last bin). |
| `labels=False` | Returns integer bin numbers instead of a categorical. |
| `ordered=True` (default) | The resulting categorical is ordered. |
| `retbins=True` | Also returns the bin edges as an array. |
| `precision=3` | Number of decimal digits shown in interval labels. |
After binning, always check isna().sum() on the result. Compare it with the number of missing values in the source column. Any extra missing values are rows that fell outside your edges.
print(default.isna().sum() - x.isna().sum()) # 1 row fell outside the binsEqual-width bins with an integer
If bins is an integer, cut splits the range from the minimum to the maximum into that many equal-width bins. It extends the minimum edge by 0.1% so the smallest value is included.
import pandas as pd
values = pd.Series([1, 2, 3, 4, 100])
equal_width = pd.cut(values, bins=3, labels=["low", "mid", "high"])
print(equal_width.value_counts().sort_index())
# low 4
# mid 0
# high 1One outlier stretched the range, so four of the five rows share a bin and the middle bin is empty. Note that value_counts reports the empty mid category with a count of zero, because categoricals remember all their categories. Equal-width bins on skewed data are rarely what you want. Use qcut or explicit edges instead.
pd.qcut for equal-sized groups
qcut takes q, either an integer number of quantile groups or a list of quantile fractions between 0 and 1.
import pandas as pd
values = pd.Series([1, 2, 3, 4, 100])
by_quantile = pd.qcut(values, q=3, labels=["low", "mid", "high"])
print(by_quantile.tolist()) # ['low', 'low', 'mid', 'high', 'high']
print(by_quantile.value_counts().sort_index().tolist()) # [2, 1, 2]With five rows and three groups the counts cannot be equal, but they are as close as possible. The outlier 100 no longer affects the edges.
You can also pass specific quantiles. This is useful when you want a tail group:
import pandas as pd
scores = pd.Series(range(1, 101))
tiers = pd.qcut(scores, q=[0, 0.5, 0.9, 1.0], labels=["bottom half", "next 40%", "top 10%"])
print(tiers.value_counts().sort_index().tolist()) # [50, 40, 10]Unlike cut, qcut always includes the lowest value, so you do not need include_lowest.
Duplicate edges in qcut
If many rows share the same value, two quantiles can land on the same number. The bin edges are then not unique and qcut raises ValueError: Bin edges must be unique. Passing duplicates="drop" removes the repeated edges, so you get fewer bins than requested.
import pandas as pd
s = pd.Series([1, 1, 1, 1, 2, 3])
binned = pd.qcut(s, q=4, duplicates="drop")
print(len(binned.cat.categories)) # 2, not 4Reusing the same bins on new data
Computing qcut separately on training data and on new data gives different edges, so the same value can land in different groups. Fit the edges once with retbins=True, then apply them to new data with cut.
import pandas as pd
train = pd.Series([10, 20, 30, 40, 50, 60, 70, 80])
labels = ["Q1", "Q2", "Q3", "Q4"]
train_bins, edges = pd.qcut(train, q=4, labels=labels, retbins=True)
print(edges.tolist()) # [10.0, 27.5, 45.0, 62.5, 80.0]
new = pd.Series([5, 25, 45, 90])
new_bins = pd.cut(new, bins=edges, labels=labels, include_lowest=True)
print(new_bins.tolist()) # [nan, 'Q1', 'Q2', nan]Values below the first edge or above the last edge become NaN. If you need to cover them, replace the outer edges with -np.inf and np.inf before calling cut.
Working with the result
Because the output is a normal categorical, the usual tools apply. Here is a short example that combines binning with grouping:
import pandas as pd
df = pd.DataFrame({"age": [5, 17, 30, 64, 80], "spend": [0, 10, 120, 90, 40]})
df["group"] = pd.cut(
df["age"], bins=[0, 18, 65, 120], labels=["child", "adult", "senior"]
)
print(df.groupby("group", observed=False)["spend"].sum().tolist()) # [10, 210, 40]Each bin you defined appears in the groupby result, even one with no rows, because all categories are kept. This is the observed behavior covered in the next chapter.
Other points to remember:
- Convert the bins to plain integers with
labels=Falseor.cat.codeswhen you want numbers for a model. The codes follow the bin order. - If you later add data with a value outside the bin range, you cannot assign it directly. The categories are fixed, so you must rebin or add a category.
- Interval categories are more compact than strings only when there are few bins, but the memory cost of either form is small. Choose by readability.
Common errors
- Counting labels wrongly. N edges need N-1 labels. A mismatch raises
ValueError: Bin labels must be one fewer than the number of bin edges. - Edges that are not monotonic. For
cut, the list of edges must increase. An unsorted list raises an error. - Treating the first edge as inclusive. See
include_lowestabove. - Expecting
qcutgroups to be exactly equal. Ties and small samples make the counts differ. - Binning before splitting data into train and test sets, then computing quantiles on the whole dataset. This leaks information from the test set. Fit edges on the training set only.
Exercise
You run pd.cut(pd.Series([0, 5, 10]), bins=[0, 5, 10], labels=["a", "b"]). What are the three results, and what single argument would change the first one so that 0 falls in "a"?
Show answer
The result is [NaN, 'a', 'b']. Bins are right-inclusive, so they are (0, 5] and (5, 10]. The value 0 is on the excluded lower edge, so it becomes NaN. Adding include_lowest=True puts 0 in the first bin, giving ['a', 'a', 'b'].
Exercise
You fit pd.qcut(train, q=4, retbins=True) and want to label a new column of values with the same four groups. Which function do you call on the new data, and which argument receives the edges?
Show answer
Call pd.cut on the new data and pass the returned edges as the bins argument, for example pd.cut(new, bins=edges, labels=labels, include_lowest=True). Calling qcut on the new data would compute different edges from the new values.