Sub topic 2
Equal-width bins with pd.cut
This chapter assumes you can build a pandas Series, read basic descriptive statistics (minimum, maximum, range), and run short Python scripts. Here you use pd.cut in its simplest form: you give it a number of bins, and it splits the range of your data into that many intervals of the same width. Later chapters cover explicit edges, interval closure, and labels in detail.
The idea: split the range, not the rows
pd.cut(x, bins=n) with an integer n does three things:
- It finds the minimum and maximum of
x, ignoring missing values. - It places
n + 1evenly spaced edges from the minimum to the maximum, which givesnintervals of equal width. - It assigns each value to the interval that contains it.
The width of each interval is (max - min) / n. This is the same rule a histogram uses. Equal width does not mean equal counts. The number of rows in each bin depends on how the values are distributed.
A first example
import pandas as pd
values = pd.Series([1, 7, 5, 4, 6, 3])
groups = pd.cut(values, bins=3)
print(groups.cat.categories)
print(groups.tolist())The minimum is 1 and the maximum is 7, so the range is 6 and each bin is 2 wide. The edges are 1, 3, 5, and 7. The categories printed are:
IntervalIndex([(0.994, 3.0], (3.0, 5.0], (5.0, 7.0]], dtype='interval[float64, right]')The first edge is 0.994, not 1.0. That is deliberate, and the next section explains why.
Why the first edge is not the minimum
By default, intervals are closed on the right. The interval (1.0, 3.0] excludes 1.0, so the minimum value 1 would have no bin. To prevent that, pd.cut moves the lowest edge down by 0.1% of the range. Here that is 6 × 0.001 = 0.006, which turns 1.0 into 0.994.
Because of this nudge, the edges you see are rarely round numbers. If you need clean boundaries such as 0, 25, 50, and 75, pass explicit edges instead.
The categorical result
pd.cut returns a Series of dtype category when you pass a Series. The categories are Interval objects, and they are ordered. You can work with the result like any other categorical column:
import pandas as pd
values = pd.Series([1, 7, 5, 4, 6, 3])
groups = pd.cut(values, bins=3)
print(groups.dtype)
print(groups.cat.categories.left.tolist())
print(groups.cat.categories.right.tolist())
print(groups.cat.ordered)The .left and .right attributes of the IntervalIndex give you the numeric edges. The ordered flag is True, so comparisons and sorting follow the interval order, not alphabetical order.
If you only need integer bin numbers, pass labels=False:
import pandas as pd
values = pd.Series([1, 7, 5, 4, 6, 3])
codes = pd.cut(values, bins=3, labels=False)
print(codes.tolist())This prints [0, 2, 1, 1, 2, 0]. The result is a plain integer Series, not a categorical. That is convenient for feeding bin positions into other calculations. It also drops the interval information, so you lose the edges unless you recompute them.
Equal width is not equal count
The main gotcha with integer bins is that the extremes control the layout. One large value stretches the range, so most of your data lands in one bin.
import pandas as pd
skewed = pd.Series([1, 2, 2, 3, 3, 3, 4, 4, 100])
bins = pd.cut(skewed, bins=4)
print(bins.value_counts().sort_index())On pandas 2.x the output is:
(0.901, 25.75] 8
(25.75, 50.5] 0
(50.5, 75.25] 0
(75.25, 100.0] 1
Name: count, dtype: int64The range is 99, so each bin is 24.75 wide. Eight of nine values fall in the first bin, and two bins are empty. value_counts still lists the empty bins because the categories exist even when no row uses them. This is useful when you want a complete histogram table. It can surprise you in a groupby, which the summaries chapter covers.
If this layout is not what you want, you have three options:
- Use
pd.qcutto get roughly equal counts per bin, covered in a later chapter. - Give explicit edges chosen from domain knowledge.
- Clip or remove the outlier before binning, if that is justified for your analysis.
Controlling the parameters
These parameters matter when bins is an integer:
| Parameter | Default | Effect |
|---|---|---|
| `bins` | required | Number of equal-width intervals. Must be at least 1. |
| `right` | `True` | If `True`, intervals are `(a, b]`. If `False`, they are `[a, b)`. |
| `labels` | `None` | Names for the bins, or `False` to return integer codes. |
| `precision` | `3` | Decimal places used when displaying interval edges. |
| `retbins` | `False` | If `True`, also return the computed edges as an array. |
The precision parameter changes only how the intervals are displayed. The stored edges keep their full floating-point values.
import pandas as pd
values = pd.Series([1, 7, 5, 4, 6, 3])
binned, edges = pd.cut(values, bins=3, retbins=True)
print(edges)
short = pd.cut(values, bins=3, precision=1)
print(short.cat.categories)The first print shows the edges [0.994, 3., 5., 7.]. The second shows categories such as (1.0, 3.0], because the display rounds 0.994 to one decimal place. Two different edges can then look identical in the printed labels. The underlying data is still correct, so rely on retbins or .left and .right when you need exact values.
Edge cases to know
- Missing values stay missing. A
NaNin the input produces aNaNin the output. It is not placed in any bin, and it does not affect the computed min and max. - A constant column does not fail. If every value is the same, the range is zero. pandas widens the range slightly around that value so it can still build edges. All rows land in the same bin, and the other bins are empty.
binsbelow 1 raisesValueError.bins=1is allowed and puts every non-missing value in a single interval.- Edges depend on the data you pass. If you bin a training set and later a new batch with
bins=4, each call computes its own edges from its own min and max. The labels will look similar, but they will mean different ranges. For consistent bins across datasets, store the edges and reuse them as explicit bins. - Integer input still gives float edges. The edges come from a linear spacing of the range, so you get values like 0.994 and 3.0 even when your data is all integers.
Common mistakes
- Assuming bins have similar counts. Check
value_counts()after binning, especially with skewed data. - Expecting round boundaries. The first edge is shifted by 0.1% of the range, and the other edges are unrounded multiples of the width.
- Comparing bins across runs. Bins from different datasets with the same
bins=ngenerally do not line up. - Reading edges from the display. Use
retbins=Trueor theIntervalIndexattributes for exact numbers.
Exercise
You run pd.cut(pd.Series([10, 20, 30, 40, 50]), bins=4). What are the width of each bin and the four intervals, assuming the default right=True? Give the lowest edge to three decimal places.
Show answer
The range is 50 - 10 = 40, so each bin is 40 / 4 = 10 wide. The edges before adjustment are 10, 20, 30, 40, 50. The lowest edge is lowered by 0.1% of the range, which is 0.04, so it becomes 9.96. The intervals are (9.96, 20.0], (20.0, 30.0], (30.0, 40.0], and (40.0, 50.0]. The value 10 falls in the first interval, 20 in the first (right edge closed), 30 in the second, 40 in the third, and 50 in the fourth.
Exercise
A Series holds 99 values between 0 and 10 and one value of 1000. You call pd.cut(series, bins=5). Roughly how many values land in the first bin, and what would you change to spread the rows more evenly?
Show answer
The range is about 1000, so each bin is about 200 wide. All 99 values between 0 and 10 fall in the first bin, and the other four bins hold only the single outlier or nothing. To spread rows more evenly, use pd.qcut(series, q=5) for equal-count bins, pass explicit edges that suit the data, or handle the outlier before binning.