Sub topic 9
Custom quantile cut points
This chapter assumes you can call pd.qcut with an integer q and read the interval labels it produces. You should also know what a quantile is. A quantile is the value below which a given fraction of the data falls. The 0.25 quantile is the first quartile.
Why pass a list instead of an integer
With an integer, q=4 asks for equal-sized groups: quartiles, deciles (q=10), and so on. Many real questions need uneven groups. Examples:
- Flag the top 10% of customers by spend.
- Separate the extreme tails from a large middle.
- Split at the median and also at the 90th percentile.
For these cases, q can be a list of fractions between 0 and 1. Each fraction becomes a cut point, and qcut computes the matching quantile of your data.
| `q` value | Meaning | Number of bins |
|---|---|---|
| `4` | Quartiles, edges at 0, 0.25, 0.5, 0.75, 1 | 4 |
| `[0, 0.5, 1]` | Split at the median | 2 |
| `[0, 0.25, 0.75, 1]` | Tails and a middle half | 3 |
| `[0, 0.9, 1]` | Bottom 90% and top 10% | 2 |
The number of bins is always one less than the number of fractions you pass.
How the fractions become bins
qcut turns each fraction into a data value with linear interpolation between neighboring values. It then hands those values to the same binning step that pd.cut uses.
Here is a complete example with the values 1 to 100:
import pandas as pd
scores = pd.Series(range(1, 101))
bands = pd.qcut(scores, q=[0, 0.25, 0.75, 1], labels=["low", "middle", "high"])
print(bands.value_counts().sort_index().to_dict())It prints {'low': 25, 'middle': 50, 'high': 25}. The middle bin holds twice as many rows as each tail, because it spans half of the cumulative distribution (0.25 to 0.75) and each tail spans a quarter.
The fraction list describes the share of rows in each bin, not the width of the bins. The widths in data units depend on how the values are distributed.
Start at 0 and end at 1
The first and last fractions decide whether every row gets a bin. To cover all the data, the list must begin with 0 and end with 1. These correspond to the minimum and the maximum.
If you leave them out, the values beyond the outermost fractions are not in any bin. They come back as NaN:
import pandas as pd
scores = pd.Series(range(1, 101))
middle_only = pd.qcut(scores, q=[0.1, 0.9])
print(middle_only.isna().sum())This prints 20. The 0.1 quantile is 10.9 and the 0.9 quantile is 90.1. The values 1 to 10 fall below the first edge, and 91 to 100 fall above the last.
This is sometimes what you want, for example to trim outliers before an analysis. If it is not, the missing endpoints are the first thing to check. A bin count that does not add up to the row count points to the same cause.
Fractions must lie between 0 and 1. A value such as 25 (meaning 25%) raises a ValueError, because the quantile function expects fractions. Keep the fractions in ascending order.
Closure and the lowest value
qcut builds right-closed intervals such as (25.75, 75.25]. It also sets include_lowest=True internally, so the minimum of your data lands in the first bin. You do not need to pass that option as you do with pd.cut.
You will see the first interval displayed with a lower edge slightly below the minimum, such as (0.999, 25.75] for the data above. The display widens that edge so the minimum value falls inside. It does not change which rows belong to which bin.
Because the edges are computed from the data, a value that sits exactly on an edge goes into the lower bin. This matters for ties. See the chapter on repeated values for how ties can collapse edges.
Labels must match the bin count
If you pass labels, you need one label per bin, which is len(q) - 1. A mismatch raises a ValueError.
import pandas as pd
amounts = pd.DataFrame({"amount": range(1, 201)})
tier = pd.qcut(amounts["amount"], q=[0, 0.9, 1], labels=["rest", "top 10%"])
print(tier.value_counts().to_dict())This prints {'rest': 180, 'top 10%': 20}. The 0.9 quantile is 180.1, so the values 181 to 200 form the top tier.
Two other label options behave the same as in pd.cut:
labels=None(the default) gives interval labels.labels=Falsegives integer bin numbers starting at 0. This is handy for sorting or arithmetic.
Recovering the edges
With custom fractions it is easy to lose track of what the cut points actually are. Use retbins=True to get them back:
import pandas as pd
scores = pd.Series(range(1, 101))
binned, edges = pd.qcut(scores, q=[0, 0.25, 0.75, 1], retbins=True)
print(edges.tolist())This prints [1.0, 25.75, 75.25, 100.0]. The edges are not whole numbers even though the data is. That is the interpolation at work: the 0.25 quantile of 100 values falls between the 25th and 26th values.
Keep these edges if you need to apply the same cut to new data. Re-running qcut on a new batch recomputes quantiles from that batch, so the thresholds shift. To apply fixed thresholds to later data, pass the saved edges to pd.cut.
Gotchas
- Ties collapse edges. If many values are identical, two fractions can map to the same value, and
qcutraises an error about non-unique bin edges. The fix isduplicates="drop", covered in the next chapter. - Dropping edges changes the bin count. After
duplicates="drop"there are fewer bins thanlen(q) - 1. Alabelslist sized for the original count then fails. Uselabels=Falseor no labels in that case. NaNinputs are ignored when computing quantiles. They stayNaNin the output. They never reach a bin.- Small samples give coarse results. With 10 rows,
q=[0, 0.9, 1]puts one row in the top bin, and the exact assignment depends on interpolation. Check counts before you rely on the groups. - Fractions describe this dataset. "Top 10%" means the top 10% of the rows you passed in. Calling
qcutper group, or on a filtered subset, gives different thresholds.
When to use custom fractions
Choose custom fractions when the group sizes carry meaning. Typical cases are the top tier, a bottom tail, or a split at a specific percentile. Use q=<integer> when you only want similar-sized groups. Use pd.cut when thresholds have meaning in the data's own units, such as age limits or price bands.
Exercise
You run pd.qcut(df["income"], q=[0.05, 0.95]) on 1,000 rows with no missing incomes. How many rows will come back as NaN, roughly, and what change to q would assign every row to a bin while keeping the 5% and 95% cut points?
Show answer
About 100 rows will be NaN: the lowest 5% (about 50 rows) fall below the first edge and the highest 5% (about 50 rows) fall above the last edge. Use q=[0, 0.05, 0.95, 1] so that the list starts at 0 and ends at 1. That gives three bins: the bottom 5%, the middle 90%, and the top 5%.
Exercise
You call pd.qcut(scores, q=[0, 0.25, 0.75, 1], labels=["low", "high"]). What happens, and how do you fix it?
Show answer
It raises a ValueError, because three bins need three labels (len(q) - 1) and you gave two. Either supply three labels, such as ["low", "middle", "high"], or change q to [0, 0.5, 1] if you want only two bins.