Sub topic 8
Equal-frequency bins with pd.qcut
This chapter assumes you can create a pandas Series, read basic descriptive statistics such as percentiles, and have seen pd.cut with explicit edges. Here you will learn how pd.qcut chooses its own edges so that each bin holds about the same number of rows.
The working model
pd.qcut is short for "quantile cut". Instead of splitting the value range into equal-width pieces, it splits the sorted data into groups of equal size. You give it the number of groups with q, and it computes the matching quantiles and uses them as bin edges.
The edges depend on the data, so they change whenever the data changes. With q=4 the edges are the minimum, the 25th, 50th and 75th percentiles, and the maximum. These give four bins, called quartiles.
A first example
import pandas as pd
scores = pd.Series(range(1, 101))
quartiles = pd.qcut(scores, q=4, labels=["Q1", "Q2", "Q3", "Q4"])
print(quartiles.value_counts().sort_index())Each label appears 25 times, because 100 values split into four equal groups. Without labels, the result holds Interval objects. The first one prints as (0.999, 25.75]. Pandas lowers the first edge slightly below the minimum so the smallest value falls inside the first bin. You do not need include_lowest=True with qcut.
Why equal counts matter
Equal-width bins on skewed data can leave most rows in one bin. Quantile bins avoid that, because the bin widths adapt to the data.
import pandas as pd
incomes = pd.Series([20, 22, 25, 27, 30, 35, 40, 200])
print(pd.cut(incomes, bins=4).value_counts().sort_index())
print(pd.qcut(incomes, q=4).value_counts().sort_index())The single value 200 stretches the range, so pd.cut puts seven of the eight values in the first bin. pd.qcut puts two values in each bin.
Useful parameters
| Parameter | Effect |
|---|---|
| `q` | An integer number of bins, or a list of fractions such as `[0, 0.5, 1]` |
| `labels` | A list with exactly one label per bin, or `False` for integer bin numbers |
| `retbins` | Also returns the computed edges |
| `duplicates` | `"raise"` (default) or `"drop"` when edges repeat |
Setting labels=False returns integer codes from 0, which is handy when you need a numeric feature instead of a categorical one.
Common errors
Repeated values can make several quantiles identical. Then two edges are equal, and qcut raises a ValueError. This often happens with data that has many zeros or ones. Passing duplicates="drop" removes the repeated edges.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
binned, edges = pd.qcut(values, q=4, duplicates="drop", retbins=True)
print(edges)The result has fewer bins than q, so a labels list of length q no longer matches and raises its own error. When you use duplicates="drop", either leave labels unset or give it the length of the reduced bin count.
Two other points to remember:
- Bins are only "equal" when values are distinct. Ties cannot be split across bins, so the counts may differ slightly.
- Edges come from the data you pass in. If you bin new data later,
qcutcomputes different edges. To reuse the old edges, save them withretbins=Trueand pass them topd.cut.
Exercise
A Series has 1,000 values, and 600 of them are 0. You call pd.qcut(s, q=5) and get a ValueError. Why does it happen, and how do you fix it?
Show answer
With 600 zeros, the 0%, 20%, 40% and 60% quantiles are all 0, so several bin edges are identical, and qcut rejects duplicate edges by default. Pass duplicates="drop" to remove the repeated edges. The result has fewer than five bins, so do not pass a labels list of length five.