Sub topic 8
Equal-frequency bins with pd.qcut
This chapter assumes you can build a pandas Series, read basic descriptive statistics such as quartiles and the median, and use pd.cut with explicit edges. Here you will learn how pd.qcut places bin edges at quantiles of your data, so each bin receives roughly the same number of rows.
What qcut does
pd.cut fixes the bin widths and lets the counts fall where they may. pd.qcut does the opposite. It fixes the counts and lets the widths follow the data. The name stands for "quantile cut".
A quantile is a value that has a given fraction of the data at or below it. The median is the 0.5 quantile. The quartiles are the 0.25, 0.5 and 0.75 quantiles. Splitting at the quartiles gives four bins that each hold about a quarter of the rows.
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 of the four labels appears 25 times. The data is the integers 1 to 100, so the quartile edges are 25.75, 50.5 and 75.25. Values 1 to 25 are at or below 25.75, so they land in Q1. The other bins follow the same pattern.
How the edges are computed
When q is an integer, qcut asks for the quantiles at 0, 1/q, 2/q, ..., 1. For q=4 those fractions are 0, 0.25, 0.5, 0.75 and 1. It computes them the way Series.quantile does, using linear interpolation between neighboring sorted values. The result is q + 1 edges that define q bins.
The edges depend entirely on the data you pass in. Run qcut on a different sample and you get different edges, even with the same q.
The first interval looks odd
qcut includes the lowest value in the first bin, as if you had passed include_lowest=True to cut. To make that work, pandas nudges the lowest edge down slightly. Printing the intervals for range(1, 101) shows (0.999, 25.75] as the first interval, not (1.0, 25.75]. The 0.999 is a display artifact of that adjustment. The value 1 is in the bin.
import pandas as pd
scores = pd.Series(range(1, 101))
print(pd.qcut(scores, q=4).cat.categories)Every other interval is closed on the right, like the default in cut.
Counts are equal only when the data allows it
"Equal frequency" is a goal, and qcut meets it only approximately. If the row count does not divide evenly, the counts differ by a row or so. Ten values split into four bins give counts of 3, 2, 2 and 3.
import pandas as pd
values = pd.Series(range(1, 11))
binned = pd.qcut(values, q=4)
print(binned.value_counts(sort=False).tolist())[3, 2, 2, 3]Repeated values cause a bigger difference. Equal values always go into the same bin, because a bin is defined by its edges and not by row position. A column where half the rows are 0 cannot be split evenly. The next chapters cover the case where the repetition is so heavy that edges collide.
Labeling the bins
The labels parameter works as in cut, with two points specific to qcut.
- Pass a list with exactly
qlabels. A list of any other length raises aValueError. - Pass
labels=Falseto get integer bin numbers from 0 toq - 1instead of intervals.
Integer codes are compact, and they suit machine-learning features or plain sorting.
import pandas as pd
income = pd.Series([12, 15, 22, 30, 41, 58, 75, 120, 300, 900])
codes = pd.qcut(income, q=5, labels=False)
print(codes.tolist())[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]The data is heavily skewed. The largest value is 900 and the median is about 50. Even so, each bin holds two rows. This is the main reason to prefer qcut for skewed data. Five equal-width bins over the range 12 to 900 would put most of these rows into the first bin.
With labels=False the result is a plain integer Series, not a categorical. You lose the ordered category type, but you gain a column that is easy to use in arithmetic.
What qcut returns
The return type depends on the input.
| Input | Result |
|---|---|
| `pd.Series` | `Series` with categorical dtype, same index as the input |
| list, tuple or NumPy array | `Categorical` object |
| `labels=False` | integer NumPy array, or integer Series for Series input |
| `retbins=True` | a tuple of the binned result and the edges |
The categorical is ordered, so comparisons such as binned >= "Q3" work when you use text labels. For a Series input, binned.cat.categories lists the bins and binned.cat.codes gives integer positions, with -1 for missing values.
Missing values
qcut ignores missing values when it computes quantiles. A NaN in the input stays NaN in the output, and it takes no part in the edge calculation. If you have 100 rows and 20 are missing, the 80 non-missing rows are split into equal bins. The 20 missing rows come back as NaN.
Because the edges come from the same data you bin, no non-missing value can fall outside the bins. This differs from cut with explicit edges, where out-of-range values become NaN. When you see NaN in a qcut result, the input was missing at that position.
import pandas as pd
values = pd.Series([1, 2, 3, 4, None, 6, 7, 8])
binned = pd.qcut(values, q=2, labels=["low", "high"])
print(binned.isna().tolist())[False, False, False, False, True, False, False, False]Using qcut results in a groupby
A binned column is a good group key. Equal-frequency bins make the groups comparable in size, so their means rest on similar amounts of data.
import pandas as pd
df = pd.DataFrame({"spend": [5, 8, 12, 20, 35, 50, 80, 200]})
df["spend_band"] = pd.qcut(df["spend"], q=2, labels=["low", "high"])
summary = df.groupby("spend_band", observed=True)["spend"].agg(["count", "mean"])
print(summary)The median of the eight values is 27.5. The low band holds 5, 8, 12 and 20, with a mean of 11.25. The high band holds 35, 50, 80 and 200, with a mean of 91.25. Both have a count of 4. Passing observed=True limits the output to categories that occur in the data. A later chapter covers summaries by bin in detail.
Parameters at a glance
| Parameter | Purpose |
|---|---|
| `x` | The 1-D data to bin |
| `q` | An integer number of quantiles, or a list of fractions between 0 and 1 |
| `labels` | A list of `q` labels, or `False` for integer codes |
| `retbins` | If `True`, also return the computed edges |
| `precision` | Number of decimal digits shown in interval labels (default 3) |
| `duplicates` | `"raise"` (default) or `"drop"` for repeated edges |
Common errors
ValueError: Bin edges must be unique. Heavy repetition in the data made two or more quantile edges equal. Theduplicatesparameter covers this, and a later chapter treats it in full.ValueError: Bin labels must be one fewer than the number of bin edges. Thelabelslist does not haveqentries. Count the bins, not the edges.- Different edges on different samples.
qcutrecomputes quantiles on every call. If you bin a training set and a test set separately, the two sets get different cut points. To reuse one set of edges, save them withretbins=Trueand apply them withpd.cut. - Fewer rows than bins. If the data has fewer distinct values than
q, edges must repeat, and you get the duplicate-edge error.
Exercise
A Series holds 12 distinct values with no missing data. You call pd.qcut(s, q=3, labels=["low", "mid", "high"]). How many rows land in each bin, and what changes if you pass labels=False instead?
Show answer
Twelve rows split into three bins gives 4 rows in each of low, mid and high, because the values are distinct and 12 divides evenly by 3. With labels=False the result is the integers 0, 1 and 2 (four of each) instead of the text labels, and it is a plain integer Series, not an ordered categorical.
Exercise
You run pd.qcut on a column of 200 values where 40 are missing. Roughly how many rows does each of five bins get, and how many NaN values appear in the output?
Show answer
The quantiles are computed from the 160 non-missing values, so each of the five bins gets about 32 rows. The 40 missing rows stay NaN in the output, so there are 40 NaN values.