Sub topic 10
Repeated values and duplicates='drop'
This chapter covers why pd.qcut can fail on data with many repeated values, what duplicates="drop" does about it, and what you give up when you use it. It assumes you know the basics of pd.qcut from the previous chapters. It also assumes you are comfortable with percentiles and with reading a pandas Series.
Why qcut can fail
pd.qcut computes quantiles of your data and uses them as bin edges. With q=4 it asks for the 0%, 25%, 50%, 75% and 100% quantiles, which gives five edges and four bins.
If one value makes up a large share of the data, several quantiles land on that same value. The edges are then no longer distinct. A bin between two equal edges would have zero width, and qcut cannot build an interval from it. By default it raises a ValueError whose message starts with Bin edges must be unique.
Data like this is common in practice:
- Counts, such as the number of purchases per customer, where most customers have 0 or 1.
- Amounts that are zero for most rows, such as refunds, discounts or ad spend.
- Ratings or scores on a small integer scale.
- Measurements rounded so coarsely that many rows tie.
A worked failure
Take eight values where five of them are 1. Sorted, they are 1, 1, 1, 1, 1, 2, 3, 4. Pandas finds quantiles by linear interpolation between the sorted values, so the edges for q=4 work out like this:
| Quantile | Position in sorted data | Edge |
|---|---|---|
| 0% | first value | 1.0 |
| 25% | between the 2nd and 3rd value | 1.0 |
| 50% | between the 4th and 5th value | 1.0 |
| 75% | between the 6th and 7th value | 2.25 |
| 100% | last value | 4.0 |
The first three edges are all 1.0. The requested bins would be (1, 1], (1, 1] and (1, 2.25], and the first two cannot be distinguished.
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("qcut failed:", str(err)[:40])This prints qcut failed: Bin edges must be unique, followed by the first part of the edge list.
What duplicates='drop' does
The duplicates parameter accepts two values: "raise" (the default) and "drop". With "drop", qcut computes the edges as usual, removes the repeated ones, and builds bins from what is left.
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)
print(binned.value_counts().sort_index())The edges that remain are 1.0, 2.25 and 4.0, so you get two bins instead of four. The first interval is displayed as (0.999, 2.25]. qcut includes the minimum value in the first bin and shows its lower edge slightly below the true value to say so. The counts are 6 and 2. Six values are at most 2.25 (five 1s and the 2). The values 3 and 4 fall in the upper bin.
The result is still a valid categorical Series. It simply has fewer categories than you asked for.
The bin count changes, so labels can break
The number of bins after dropping depends on the data. This matters when you pass labels. A list of four labels is wrong when only two bins come out, and qcut raises a ValueError because the label count does not match the bin count.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
try:
pd.qcut(values, q=4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop")
except ValueError:
print("label count does not match the number of bins")You have three ways to deal with this:
- Omit
labelsand let the intervals name the bins. - Call
qcutonce withretbins=True, checklen(edges) - 1, then build labels of that length. - Generate labels from the edges after the fact, for example by formatting each interval.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
_, edges = pd.qcut(values, q=4, duplicates="drop", retbins=True)
labels = [f"Q{i + 1}" for i in range(len(edges) - 1)]
binned = pd.qcut(values, q=4, labels=labels, duplicates="drop")
print(binned.value_counts().sort_index())This runs qcut twice, which is cheap for most data sets, and the labels always match the bins that actually exist.
What you lose when you drop
Dropping edges removes the error, but it changes the meaning of the result.
- Fewer bins than requested. A column built with
q=4may contain two or three categories. Code that assumes four, such as a fixed list of labels or a chart with four colors, will break or mislead. - Unequal bin sizes.
qcutis chosen for equal-frequency bins, but ties make that impossible. In the example above the bins hold 6 and 2 rows. The big bin exists because five rows share the value1, and no cut point can separate identical values. - Data-dependent output. The same code on a different month of data may produce three bins one time and four the next. That makes
qcuthard to use in a pipeline whose output must have a stable shape.
A tied value always lands in a single bin. A bin boundary is a number, and equal numbers fall on the same side of it. This is correct behavior, not a bug.
Other ways to handle heavy ties
duplicates="drop" is not always the best answer. These alternatives suit different goals.
Use pd.cut with explicit edges
If the bins should have a stable meaning, such as "0", "1 to 5" and "6 or more", write the edges yourself with pd.cut. The result does not depend on how the data is distributed. The same duplicates parameter exists on pd.cut, but it only matters if you pass repeated edges by mistake.
Rank first to force equal-sized bins
If you need equal-sized bins even among tied values, convert the values to ranks with method="first". Each row then gets a unique rank, so the quantile edges are distinct.
import pandas as pd
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
ranks = values.rank(method="first")
quartiles = pd.qcut(ranks, q=4, labels=["Q1", "Q2", "Q3", "Q4"])
print(quartiles.value_counts().sort_index())Each quartile gets two rows. The cost is that identical values can end up in different bins, and which of the tied rows goes where depends on their order in the data. Use this only when the equal sizes matter more than keeping equal values together, for example when you split rows into balanced groups for an experiment.
Treat the dominant value separately
When one value, usually zero, dominates, you can give it its own category and apply qcut to the rest.
import pandas as pd
spend = pd.Series([0, 0, 0, 0, 0, 0, 5, 10, 20, 40])
positive = spend[spend > 0]
tiers = pd.qcut(positive, q=2, labels=["low", "high"])
result = pd.Series("none", index=spend.index, dtype="object")
result.loc[positive.index] = tiers.astype(str)
print(result.value_counts().sort_index())The six zero rows become none. Among the four positive rows, the median is 15, so 5 and 10 are low and 20 and 40 are high. The result is three groups with clear meanings, and no edges are dropped.
Choosing an approach
| Goal | Approach |
|---|---|
| Get a result and accept fewer bins | `qcut` with `duplicates="drop"` |
| Bins with fixed, meaningful boundaries | `pd.cut` with explicit edges |
| Exactly equal group sizes, ties may split | `rank(method="first")` then `qcut` |
| One value dominates and deserves its own group | Separate that value, then `qcut` the rest |
Summary of behavior
- Repeated values make several quantiles equal, so some edges are identical.
- By default,
qcutraisesValueError: Bin edges must be unique. duplicates="drop"removes repeated edges and returns fewer bins.- Combine it with
retbins=Trueto see which edges survived. - Labels must match the number of bins that remain, not the number you asked for.
- Alternatives such as
pd.cut, ranking, or splitting out the dominant value give more control when ties are heavy.
Exercise
A column has 100 rows, 70 of which are 0, and the rest are positive and distinct. You call pd.qcut(col, q=4) and get a ValueError. After adding duplicates="drop", how many bins do you expect at most, and why is the first bin much larger than 25 rows?
Show answer
The 0%, 25% and 50% quantiles all fall inside the 70 zeros, so those three edges are all 0.0. After dropping, the edges are 0.0, the 75% quantile and the maximum, which gives at most two bins. All 70 zeros must go in the first bin because equal values cannot be split across a boundary, so that bin holds at least 70 rows, far more than 25.
Exercise
You run pd.qcut(values, q=4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop") and it raises a ValueError about labels. What happened, and how can you build labels that always match?
Show answer
Dropping repeated edges left fewer than four bins, so four labels no longer match the bin count. Call pd.qcut once with retbins=True, compute n = len(edges) - 1, build labels such as [f"Q{i + 1}" for i in range(n)], and call qcut again with those labels. Alternatively, omit labels and use the intervals.