Sub topic 10
Repeated values and duplicates='drop'
This chapter assumes you can use pd.qcut with an integer number of quantiles and that you know what a quantile is. It covers why qcut can fail on data with many repeated values and how to handle that.
Why qcut can fail
pd.qcut computes cut points at evenly spaced quantiles. With q=4 it needs the 0%, 25%, 50%, 75% and 100% quantiles. These become the bin edges.
If one value makes up a large share of the data, several quantiles land on that same value. The edges then contain repeats, and a bin with identical lower and upper edges has zero width. No row could ever fall into it.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
try:
pd.qcut(values, q=4)
except ValueError as err:
print(err)Five of the eight values are 1. The 25% and 50% quantiles are both 1, and so is the minimum. The edges are [1, 1, 1, 2.25, 4]. By default qcut raises a ValueError whose message starts with "Bin edges must be unique".
Dropping the repeated edges
Set duplicates="drop" to remove repeated edges before the bins are built. Add retbins=True to see which edges remain.
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)
print(binned.cat.categories)The edges print as [1. 2.25 4. ]. Three edges define two bins instead of four. The first bin covers 1 through 2.25 and holds six rows. The second covers 2.25 through 4 and holds two rows. The bins are no longer equal-sized, because the data cannot be split into four equal groups. All five 1s must land in the same bin.
The first bin's lower bound is displayed as 0.999 rather than 1. qcut includes the lowest edge, and pandas widens the printed bound slightly so the minimum falls inside the interval.
Labels must match the surviving bins
Dropping edges changes how many bins exist, and labels has to match that new count. A list of four labels fails here.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
binned = pd.qcut(values, q=4, labels=["low", "high"], duplicates="drop")
print(binned.tolist())The code runs because two labels fit two bins. Four labels would raise a ValueError saying the labels must be one fewer than the number of bin edges.
You can't always know the surviving bin count in advance. Two ways around this:
- Run once with
retbins=True, checklen(edges) - 1, then write the labels. - Pass
labels=Falseto get integer bin codes (0, 1, ...) and name them afterwards.
When dropping is the wrong fix
duplicates="drop" hides the fact that your data is heavily skewed. Before using it, consider these options:
| Situation | Better approach |
|---|---|
| One value dominates, such as many zeros | Separate that value into its own group, then `qcut` the rest |
| You need a fixed number of bins | Use `pd.cut` with explicit edges |
| Equal-sized groups are required | Rank first with `values.rank(method="first")`, then `qcut` the ranks |
Ranking with method="first" gives every row a unique rank, so ties are split arbitrarily. Rows with identical values then end up in different bins, which may be misleading.
Exercise
A Series contains ten zeros and the values 5 and 9. You call pd.qcut(s, q=4, duplicates="drop"). Why do you get fewer than four bins, and how can you check how many?
Show answer
The 0%, 25% and 50% quantiles are all 0, so the edges repeat and are dropped. Only unique edges remain, which means fewer bins than requested. Pass retbins=True and compute len(edges) - 1 to count the bins.