kmail.at
contact

elsewhere

EnglishEN
← learning

pandas · difficulty ◆◆

pandas qcut() — bucket a column into equal-sized percentile cohorts

cut() splits the range, qcut() splits the rows — four buckets with the same number of people in each.

Every "top 10% of customers" slide was built on a threshold somebody guessed. qcut() computes the threshold from the data instead.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-25 · 4 min read

$ pd.qcut()
0.8.0
added in pandas

29 June 2012 — the same release that introduced cut()

6
parameters

x, q, labels, retbins, precision, duplicates — that is the whole signature

0.23.0
duplicates= arrived

May 2018, GH 20947 — 'drop' instead of raising on tied edges

What it does

qcut() takes one numeric column and a q, computes the quantile edges from that column, and returns an ordered categorical — one band per row. Pass an integer for equal-count buckets (4 quartiles, 10 deciles) or a list of quantiles ([0, .5, .9, 1]) for unequal bands like bottom half / middle 40% / top 10%. labels= names the bands low-to-high, labels=False gives integer codes, retbins=True hands the computed edges back. Unlike cut(), you never type a threshold: the data picks them.

Why it matters

Real columns are skewed. Spend, revenue, session length, file size — a handful of whales and a long tail of near-zeros. cut() on that data produces one bin holding 90% of the rows and three bins holding the rest, which is a useless chart. qcut() guarantees the same row count in every bucket, which is exactly what a cohort analysis, an A/B split or a decile report needs. It is the difference between "customers over 1000 EUR" (a business rule) and "the top quarter of customers" (a relative position).

Example

$ import pandas as pd

cust = pd.DataFrame({
    "customer": ["Ada", "Bo", "Chen", "Dara", "Emil", "Fay",
                 "Gus", "Hana", "Ivo", "Jun", "Kai", "Lena"],
    "spend_eur": [120, 340, 210, 1890, 460, 275,
                  980, 150, 1420, 630, 305, 720],
})
cust["tier"] = pd.qcut(cust["spend_eur"], 4,
                       labels=["bronze", "silver", "gold", "platinum"])
print(cust.groupby("tier", observed=True)["spend_eur"].agg(["count", "min", "max", "mean"]).round(2))
          count  min   max     mean
tier                               
bronze        3  120   210   160.00
silver        3  275   340   306.67
gold          3  460   720   603.33
platinum      3  980  1890  1430.00

Quartiles on a customer table, three customers per tier. The result is an ordered Categorical, so groupby comes back bronze -> platinum instead of alphabetically — and the equal counts are the whole point: cut() on this column would have put nine of twelve customers in one band.

$ import pandas as pd

# support tickets: most resolve the same day, a few drag on for weeks
hours = pd.Series([0, 0, 0, 0, 0, 0, 0, 1, 3, 5, 8, 12, 19, 45],
                  name="resolve_hours")
try:
    pd.qcut(hours, 4)
except ValueError as exc:
    print(type(exc).__name__ + ":", exc)

print()
print(pd.qcut(hours, 4, duplicates="drop").value_counts().sort_index())
ValueError: Bin edges must be unique: Index([0.0, 0.0, 0.5, 7.25, 45.0], dtype='float64', name='resolve_hours').
You can drop duplicate edges by setting the 'duplicates' kwarg

resolve_hours
(-0.001, 0.5]    7
(0.5, 7.25]      3
(7.25, 45.0]     4
Name: count, dtype: int64

Seven tickets resolved in zero hours. Those ties collapse the 25th percentile edge onto 0.0, and qcut refuses to guess: ValueError. duplicates='drop' keeps only the distinct edges, so you get three bands where you asked for four — the quartiles are impossible on this distribution, and pandas answers by handing you a different shape rather than a wrong one.

$ import pandas as pd

stores = pd.DataFrame({
    "region": ["North", "North", "North", "North",
               "South", "South", "South", "South"],
    "store":  ["N1", "N2", "N3", "N4", "S1", "S2", "S3", "S4"],
    "revenue_k": [410, 95, 260, 180, 88, 305, 150, 42],
})
stores["tier"] = stores.groupby("region")["revenue_k"].transform(
    lambda s: pd.qcut(s, 2, labels=["low", "high"])
)
print(stores.sort_values(["region", "revenue_k"]).to_string(index=False))
region store  revenue_k tier
 North    N2         95  low
 North    N4        180  low
 North    N3        260 high
 North    N1        410 high
 South    S4         42  low
 South    S1         88  low
 South    S3        150 high
 South    S2        305 high

Inside groupby().transform(), qcut bins within each region instead of across the company: North's 95k store is 'low' and so is South's 88k one, while 305k is 'high'. Ranking every store against the whole estate would compare Dammam against Riyadh and call it performance. transform keeps the original index, so the new column drops straight back onto the frame.

$ import pandas as pd

baskets = pd.Series([12, 18, 23, 31, 44, 52, 61, 78, 95, 105, 340],
                    name="basket_eur")
band, edges = pd.qcut(baskets, [0, 0.5, 0.9, 1.0],
                      labels=["bottom half", "middle 40%", "top 10%"],
                      retbins=True)
print(pd.DataFrame({"basket_eur": baskets, "band": band}).to_string(index=False))
print()
print("edges:", edges.round(2).tolist())
print("top 10% starts at", round(edges[2], 2), "EUR")
 basket_eur        band
         12 bottom half
         18 bottom half
         23 bottom half
         31 bottom half
         44 bottom half
         52 bottom half
         61  middle 40%
         78  middle 40%
         95  middle 40%
        105  middle 40%
        340     top 10%

edges: [12.0, 52.0, 105.0, 340.0]
top 10% starts at 105.0 EUR

Pass the quantiles themselves when the bands are not equal-sized: bottom half, middle 40%, top 10%. retbins=True hands back the euro edges — 105.0 is the number you quote when someone asks where 'top 10%' starts, and the number you store if next quarter must use the same bands.

Common flags

q
int -> that many equal-count buckets (4 quartiles, 10 deciles); list of floats -> your own percentile edges, e.g. [0, .5, .9, 1]
labels
Names for the bands, ordered low -> high; pass False to get integer codes 0..n-1 instead of Interval objects
retbins
Return (result, edges) — the edge array is the only way to replay last month's bands on next month's data
duplicates
'raise' by default. 'drop' discards tied edges instead of raising — the flag you need on any column with a pile of identical values
precision
3 by default; changes the printed edge labels only, not which row lands in which bin
q as a list
Must run 0 -> 1 to cover everything: values outside the outermost edges come back as NaN, not as the first or last band

History

Added in pandas 0.8.0 — 29 June 2012, next to cut()

qcut() shipped in the same release as cut(), and the 0.8.0 release notes name the source plainly: "New cut and qcut functions (like R's cut function) for computing a categorical variable from a continuous variable by binning values either into value-based (cut) or quantile-based (qcut) bins." In R you had to write it yourself — cut(x, breaks = quantile(x, probs = seq(0, 1, .25))) — and qcut() folded those two calls into one. The same release renamed Factor to Categorical, which is why early qcut() output looks like a labelled factor rather than the Interval dtype you get today.

0.23.0, May 2018: the duplicates flag

For six years the failure mode was a hard ValueError: "Bin edges must be unique". Any column with a floor of identical values — zero-hour tickets, zero-session users, minimum-order fees — collapsed the quantile edges and killed the call. pandas 0.23.0 added duplicates='raise'|'drop' (GH 20947) to cut(), and qcut() shares the same binning code, so it inherited the escape hatch. The design decision worth knowing: 'drop' does not invent a fourth band, it returns three. pandas reports the real shape of your distribution instead of the shape you asked for.

Under the hood

Under the hood: .quantile() then cut()

There is no separate algorithm. pandas builds the edges with quantiles = np.linspace(0, 1, q + 1) for an integer q — nudging each one up with np.nextafter where it is not exactly representable in base 2, which is where edges like 27.657000000000004 come from — then calls x.to_series().dropna().quantile(quantiles) and hands the result to the same _bins_to_cuts machinery cut() uses, with include_lowest=True. Two consequences fall out of that three-line implementation. First, NaNs are dropped before the quantiles are computed and come back as NaN in the output, so missing values never shift the bands. Second, the edges are computed with Series.quantile's default linear interpolation, meaning the 75th percentile of four values is an average of the two middle ones, not a value that exists in your data — which is exactly why the edges can tie and why duplicates matters.

Fun facts

Pros & cons

pros

  • + Equal row counts per bucket, so a skewed column does not collapse into one giant bin the way equal-width cut() does
  • + Returns an ordered Categorical, so groupby, sort_values and plots follow bronze -> platinum without a manual categories list
  • + The thresholds are computed, not typed — nobody has to defend why the line sits at exactly 1000 EUR

cons

  • − Raises on tied quantile edges (or silently returns fewer bins with duplicates='drop') on the floored, zero-heavy columns that are most common in production
  • − Edges move whenever the data moves: this month's 'platinum' is not last month's, so the label is not comparable across periods unless you capture retbins
  • − The bands are relative, so a genuinely bad month still produces a top decile — qcut() always finds winners

Takeaways

  1. 1Ask "top N%?" -> qcut(). Ask "over 1000 EUR?" -> cut(). The question picks the function, not the other way round.
  2. 2Set duplicates='drop' the moment the column has a floor of identical values, and read the band count in the output — three bands when you asked for four is the real answer.
  3. 3Capture retbins=True and store the edges whenever the bands go into a recurring report; qcut() recomputes from whatever data it is given.
  4. 4Bin inside the group with groupby().transform() when cohorts should be measured against peers, not against the whole table.

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning