Knowledge base / Python

pandas qcut: quantiles, labels and duplicate bin edges

I use eight explicit values to show every assignment and the boundaries of four bins. Then I explain why tied values can prevent the requested number of groups.

Kajo RudzińskiPublished Updated 5 min read

A sorter distributes cubes into compartments of different widths in yellow and navy pixel art.

When I want to group observations by their position in a distribution, I would consider pd.qcut(). A typical question is which values belong to the bottom quarter and which belong to the top quarter. The boundaries then depend on the data. If I need fixed thresholds defined by a business rule, I would choose an approach that records those thresholds explicitly.

Below, I use synthetic amounts and the behaviour described in the pandas 3.1 documentation. The example is small enough to follow by hand. Understanding every boundary and assignment matters more than adding attractive names. A label such as high cannot tell the reader which population defined that category or whether the boundary will stay the same next month.

What qcut accepts

The qcut reference gives this signature:

pd.qcut(x, q, labels=None, retbins=False, precision=3, duplicates="raise")

x contains one-dimensional values. Setting q=4 requests four quantile bins. You can also supply quantile levels, such as [0, 0.5, 1] for two groups. These are levels between zero and one, rather than thresholds expressed in the unit of your observations.

The default labels=None leaves interval descriptions. A custom list names the groups, while labels=False returns codes starting at zero. A Series input retains its index in the result; with labels, the output is a categorical Series. I would keep the original amounts alongside it so that each assignment can be inspected and explained.

A complete example with eight values

Assume eight observations, A through H. Both language versions use identical data and neutral Q1 to Q4 labels, making the results easy to compare.

import pandas as pd

amounts = pd.Series(
    [10, 20, 30, 40, 50, 60, 70, 80],
    index=list("ABCDEFGH"),
    name="amount",
)
groups, edges = pd.qcut(
    amounts,
    q=4,
    labels=["Q1", "Q2", "Q3", "Q4"],
    retbins=True,
)

The edges are 10, 27.5, 45, 62.5 and 80. In this particular example, each bin contains two observations:

Observation Amount Group
A 10 Q1
B 20 Q1
C 30 Q2
D 40 Q2
E 50 Q3
F 60 Q3
G 70 Q4
H 80 Q4

Why is the first internal boundary 27.5? With default linear interpolation, the position of quantile 0.25 among eight sorted observations is 1.75, counting from zero. That lies three quarters of the way from 20 to 30. The median is halfway between 40 and 50, giving 45. The upper quartile similarly lies between 60 and 70, at 62.5. Series.quantile documents the interpolation rule.

A value equal to a right boundary belongs to the interval ending there, and the minimum is included in the first bin. The first interval label may display a slightly lowered left edge. I would retain edges returned by retbins=True rather than copying rounded category descriptions. The precision setting concerns interval labels; it is not a way to round the original amounts.

Ties can reduce the number of bins

Now consider four tens and four twenties. The quantile boundaries are 10, 10, 15, 20, 20. Some edges repeat. The default duplicates="raise" reports an error because four distinct intervals cannot be built from those edges.

tied = pd.Series([10, 10, 10, 10, 20, 20, 20, 20])
tied_groups, tied_edges = pd.qcut(
    tied, q=4, duplicates="drop", retbins=True
)

Dropping repeated edges leaves 10, 15, 20, which define two bins. The tens belong to the first and the twenties to the second. A list of four labels would no longer fit. I would inspect the actual boundaries before choosing names and deciding whether this smaller number of groups still serves the analysis.

The drop option removes bin edges rather than repeated customers or amounts. If you require exactly equal counts despite ties, you need an additional rule for separating equal values. That changes the meaning of the segmentation. I would avoid presenting arbitrary row order as a meaningful distinction between observations with the same measured amount.

Identical cubes enter two shared compartments instead of being artificially divided into four.

qcut and cut answer different questions

qcut finds boundaries from sample quantiles. cut can receive explicit edges, including unevenly spaced ones. Supplying an integer number of bins to cut is the case that creates equal-width intervals. Describing the entire function as supporting only equal spacing would therefore leave out an important use.

Imagine a fixed amount threshold for special handling. Its meaning should remain stable even in a quiet sales month. Quartiles instead describe position relative to the chosen sample. Two observations with the same amount can receive different labels in different months if boundaries are recalculated each time using a different distribution.

I would record the reference period and population with the segments. Equal customer counts do not imply equal revenue or equal business value. A top-quartile label also says little about a customer’s permanent characteristics. It describes one variable in one population. That population and its boundaries can change, so the report needs to make the reference clear.

Applying saved boundaries to new data

To classify new observations against the earlier division, use the saved edges. Here, edges comes from the first example. The quantiles are not recalculated from the new amounts.

new_amounts = pd.Series([10, 45, 90])
new_groups = pd.cut(
    new_amounts,
    bins=edges,
    labels=["Q1", "Q2", "Q3", "Q4"],
    include_lowest=True,
)

Ten belongs to Q1, 45 to Q2, and 90 has no category because it exceeds the maximum edge of 80. Setting include_lowest=True includes the lower boundary of 10. Missing inputs and values outside the saved range need an explicit policy. I would display their count beside the segmentation before comparing the groups or interpreting a change.

A short interpretation exercise

Add another observation with amount 40 to the first table. Consider whether recalculating the quantiles should preserve the same boundaries. Then decide whether the task is to describe position in the new sample or compare against the old thresholds. That question should come before choosing the function.

Finally, inspect every assignment, group counts and observations without a category. If your task only needs fixed thresholds, continue with the entry on pandas cut. I want the segment name to have a meaning I can explain to the reader, rather than relying on the reader to infer the rule from a label.

Key takeaways

Does qcut always produce exactly equal group sizes?

No. Small samples and tied values can produce unequal groups or duplicate boundaries. Identical values are not arbitrarily split across intervals just to equalise counts.

What is the default value of labels?

The default is labels=None, which represents groups as intervals. A list supplies custom names, while labels=False returns bin codes starting at zero.

What does duplicates='drop' do?

It removes repeated bin edges, so fewer bins may remain than requested. It does not remove duplicate observations. Custom labels must match the number of bins actually created.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.