TExcelTAD
Home › pandas › Binning with cut() and qcut()

Binning with cut() and qcut()

Binning turns a continuous number into a category by putting it in a range ("bin"): ages into age groups, incomes into brackets, temperatures into "cold/mild/hot". pandas has two functions for this:

Function Bins are…
pd.cut() defined by value boundaries (equal width, or edges you choose)
pd.qcut() defined by quantiles, so each bin holds about the same number of rows

cut() with your own edges

python · try it yourself
import pandas as pd

guests = pd.DataFrame({
    "name": ["Ana", "Ben", "Cyd", "Dan", "Eve", "Fox", "Gil"],
    "age": [4, 15, 22, 37, 45, 68, 81],
})
guests["group"] = pd.cut(guests["age"], bins=[0, 12, 17, 64, 120])
print(guests)
print(guests["group"].value_counts(sort=False))
  name  age      group
0  Ana    4    (0, 12]
1  Ben   15   (12, 17]
2  Cyd   22   (17, 64]
3  Dan   37   (17, 64]
4  Eve   45   (17, 64]
5  Fox   68  (64, 120]
6  Gil   81  (64, 120]
group
(0, 12]      1
(12, 17]     1
(17, 64]     3
(64, 120]    2
Name: count, dtype: int64

The interval (17, 64] means "more than 17, up to and including 64". The right edge is included by default; pass right=False to include the left edge instead.

Labels

Interval notation is precise but not friendly. labels= names each bin:

python · try it yourself
import pandas as pd

ages = pd.Series([4, 15, 22, 37, 45, 68, 81])
groups = pd.cut(ages, bins=[0, 12, 17, 64, 120],
                labels=["child", "teen", "adult", "senior"])
print(groups.to_list())
print(groups.dtype)
['child', 'teen', 'adult', 'adult', 'adult', 'senior', 'senior']
category

The result is a categorical column whose categories keep their natural order (child < teen < adult < senior), which makes sorting and plotting come out right.

Equal-width bins

Passing a number instead of a list splits the range from min to max into that many equal-width bins:

python · try it yourself
import pandas as pd

temps = pd.Series([3.5, 8.0, 12.4, 15.0, 19.9, 24.2, 30.0])
print(pd.cut(temps, bins=3).value_counts(sort=False))
print(pd.cut(temps, bins=3, labels=["cold", "mild", "hot"]).to_list())
(3.474, 12.333]     2
(12.333, 21.167]    3
(21.167, 30.0]      2
Name: count, dtype: int64
['cold', 'cold', 'mild', 'mild', 'mild', 'hot', 'hot']

pandas extends the lowest edge slightly (to just under 3.5) so the minimum value is included.

qcut(): equal-sized groups

qcut() chooses the edges so each bin gets roughly the same number of rows. Splitting into 4 gives quartiles; into 10, deciles:

python · try it yourself
import pandas as pd

spend = pd.Series([12, 18, 25, 31, 40, 55, 70, 95, 140, 410],
                  index=[f"c{i}" for i in range(1, 11)])
tiers = pd.qcut(spend, q=4, labels=["Q1", "Q2", "Q3", "Q4"])
print(tiers.value_counts(sort=False))
print(pd.qcut(spend, q=4).cat.categories)
Q1    3
Q2    2
Q3    2
Q4    3
Name: count, dtype: int64
IntervalIndex([(11.999, 26.5], (26.5, 47.5], (47.5, 88.75], (88.75, 410.0]], dtype='interval[float64, right]')

Each quartile has 2 or 3 customers even though the spending values are very unevenly spread. With cut(spend, 4) almost everyone would land in the lowest bin because of the single 410 outlier.

Using bins in an analysis

Once values are binned, they behave like any category, perfect for groupby:

python · try it yourself
import pandas as pd

homes = pd.DataFrame({
    "size_m2": [35, 48, 62, 75, 88, 103, 120, 150],
    "price_k": [180, 230, 270, 310, 355, 410, 470, 560],
})
homes["size_band"] = pd.cut(homes["size_m2"], bins=[0, 50, 100, 200],
                            labels=["<50", "50-100", "100+"])
print(homes.groupby("size_band", observed=True)["price_k"].agg(["count", "mean"]).round(1))
           count   mean
size_band
<50            2  205.0
50-100         3  311.7
100+           3  480.0

observed=True tells groupby to show only bins that actually contain data.

Test yourself

What does the interval (10, 20] include?

  1. 10 and 20
  2. 10 but not 20
  3. 20 but not 10
  4. Neither 10 nor 20

You want 5 groups with roughly the same number of customers each. Which function?

  1. pd.cut(x, 5)
  2. pd.qcut(x, 5)
  3. x.value_counts(5)
  4. x.round(5)

What dtype does pd.cut return?

  1. object
  2. float64
  3. category
  4. interval string