Sub topic 12
Choosing between cut and qcut
This chapter assumes you can already call pd.cut and pd.qcut with edges, labels and retbins, and that you know what a quantile is. It does not teach the syntax again. It covers how to decide which function fits a task, what goes wrong when you choose badly, and how to combine them.
The one difference that matters
Both functions turn numbers into ordered categories. They differ in what they hold fixed:
pd.cutfixes the edges. You supply them, or pandas spaces them evenly across the range. The number of rows in each bin is whatever the data produces.pd.qcutfixes the row counts. Pandas computes the edges from the data's quantiles so each bin holds roughly the same number of rows. The edges are whatever the data produces.
Everything else in this chapter follows from this. Ask which of the two you need to control: the meaning of each bin, or the size of each bin.
Decision criteria
| Question | Points to `cut` | Points to `qcut` |
|---|---|---|
| Do the bin boundaries have meaning outside the data? | Yes, such as legal age limits, tax brackets or grade thresholds. | No, boundaries are only a means of ranking. |
| Do you need comparable group sizes? | No. | Yes, for example when comparing deciles or building balanced groups. |
| Is the distribution skewed or has outliers? | Risky with an integer bin count. Fine with hand-picked edges. | Handles skew well, because edges follow the data. |
| Must the same bins apply to next month's data? | Yes. Fixed edges stay fixed. | Only if you save and reuse the edges. |
| Must a reader see what a bin means? | Edges like `(18, 65]` are self-explanatory. | Edges such as `(25.75, 30.5]` are data-dependent and need explaining. |
Seeing the difference on skewed data
Incomes are a classic skewed variable: most values are clustered, and a few are very large. This example uses thousands of dollars, with one extreme value.
import pandas as pd
income = pd.Series([20, 22, 25, 28, 30, 31, 35, 40, 45, 400])
equal_width = pd.cut(income, bins=3)
equal_count = pd.qcut(income, q=4)
print(equal_width.value_counts().sort_index().tolist())
print(equal_count.value_counts().sort_index().tolist())The output is:
[9, 0, 1]
[3, 2, 2, 3]With bins=3, pandas splits the range 20 to 400 into three equal widths of about 127. Nine of ten values fall into the first bin, and the middle bin is empty. The single outlier determines where the edges are, so the binning tells you almost nothing about the typical values.
qcut places edges at the quartiles, so the outlier only affects the top bin's upper edge. The counts are 3, 2, 2 and 3 rather than exactly 2.5 each, because ten rows cannot split evenly into four.
Failure modes of cut
Outliers distort integer bin counts. The example above shows this. If you want equal-width bins on skewed data, either clip or filter the outliers first, or choose edges by hand after looking at the distribution.
Empty bins are kept. cut returns a categorical that remembers every category, including those with no rows. This is useful for reports with a stable set of rows, but it can surprise you in a groupby unless you pass observed=True.
Hand-picked edges can miss data. Any value outside the outer edges becomes NaN. When the data may change, use -np.inf and np.inf as the outer edges so nothing is dropped.
import numpy as np
import pandas as pd
ages = pd.Series([-1, 5, 30, 70, 130])
bins = [-np.inf, 18, 65, np.inf]
print(pd.cut(ages, bins=bins, labels=["child", "adult", "senior"]))This keeps invalid-looking ages such as -1 and 130 in the end bins rather than silently turning them into NaN. If those values are errors, you may prefer the NaN and a separate check, so decide this deliberately.
Failure modes of qcut
Ties break the equal-size promise. Equal values always land in the same bin. If 60% of a column is zero, no choice of quantiles can give four balanced bins.
Repeated edges raise an error. When ties make several quantile edges identical, qcut raises ValueError by default. Passing duplicates="drop" removes the repeated edges, but you then get fewer bins than you asked for.
Labels must match the surviving bins. If you pass labels of length four and duplicates="drop" leaves three bins, pandas raises a ValueError because the counts disagree. Either omit labels, or inspect the edges first with retbins=True and build labels to match.
import pandas as pd
values = pd.Series([0, 0, 0, 0, 0, 0, 2, 5, 9, 14])
binned, edges = pd.qcut(values, q=4, duplicates="drop", retbins=True)
print(len(edges) - 1, "bins survived")
print(edges)Edges are not stable. Run qcut on January data and on February data, and the quartile edges differ. A row labelled "Q4" in one month may not be comparable with "Q4" in the next. This matters for any model or report that compares across time.
Labels hide values. The label "Q3" tells a reader nothing about the actual range. When you publish results, include the edges in the output or in a note.
Combining the two: learn edges with qcut, apply them with cut
You can get data-driven edges that stay fixed. Compute the quantile edges once on a reference dataset with retbins=True, then apply them to new data with cut. This is the usual pattern when you must score new data with the same bins as the training set.
import numpy as np
import pandas as pd
train = pd.Series([10, 12, 15, 18, 20, 25, 30, 40, 55, 80])
new = pd.Series([5, 14, 33, 200])
_, edges = pd.qcut(train, q=4, retbins=True)
edges[0] = -np.inf
edges[-1] = np.inf
print(pd.cut(new, bins=edges, labels=["Q1", "Q2", "Q3", "Q4"]))Two details matter. First, qcut returns the lowest edge slightly below the minimum, and the top edge exactly at the maximum. New data beyond either end would become NaN, so replacing the outer edges with infinities avoids that. Second, cut here uses the default right-closed intervals, which match what qcut produces, so rows at an edge land in the same bin in both functions.
If you want to keep the intervals themselves rather than an edges array, you can build an IntervalIndex and pass it as bins. Both approaches give the same result for this purpose, and the edges array is shorter to write.
Practical guidance
- Start from the question. If the answer must be phrased as "people aged 18 to 65", use
cut. If it must be phrased as "the top 10% of customers", useqcut. - Look at the distribution before using an integer bin count with
cut. Checkdescribe()or a histogram, and compare the maximum with the 75th percentile. - After either call, check
value_counts().sort_index(). Empty bins or heavily uneven bins are a signal that the method does not suit the data. - For anything you will reuse, store the edges, not the labels.
- Decide explicitly what should happen to values outside your range, and make the edges reflect that decision.
Exercise
A column of transaction amounts has a median of 20, a 75th percentile of 45 and a maximum of 50,000. You call pd.cut(amounts, bins=4) and almost every row falls in the first bin. Why does this happen, and name two ways to fix it.
Show answer
With an integer bin count, cut splits the range from minimum to maximum into equal widths. The maximum of 50,000 makes each bin about 12,500 wide, so nearly all values below 45 fall in the first bin. One fix is pd.qcut(amounts, q=4), which places edges at quartiles. Another is pd.cut with hand-chosen edges such as [0, 10, 50, 200, np.inf], or clipping or filtering the outliers before binning.
Exercise
You build quartile groups with pd.qcut on this month's sales and save the group labels. Next month you run pd.qcut again on the new data and compare the "Q4" groups across months. What is wrong with this approach, and how would you fix it?
Show answer
The quartile edges depend on each month's data, so "Q4" covers a different value range each month and the groups are not comparable. Compute the edges once with retbins=True on a reference period, replace the outer edges with -np.inf and np.inf, and apply them to each month with pd.cut(new_data, bins=edges, labels=...).