Sub topic 11
Inspecting the computed edges with retbins
This chapter assumes you can call pd.cut and pd.qcut, that you know what a pandas Series is, and that you understand percentiles. Here you learn how to get back the bin edges that pandas computed, and what to do with them.
Why you need the edges
When you give pd.cut a list of edges, you already know them. In two common cases you don't:
- You pass an integer to
pd.cut, such asbins=3. Pandas computes the edges from the minimum and maximum. - You use
pd.qcut. Pandas computes the edges from the data's quantiles.
In both cases the printed intervals show the edges, but only to 3 digits of precision, and only inside a categorical column. If you want the exact numbers as an array, you set retbins=True.
With retbins=True, both functions return a tuple of two objects:
| Position | Object | Description |
|---|---|---|
| First | Series or Categorical | The binned values, the same result you get without `retbins` |
| Second | NumPy array | The bin edges, as floats for computed edges |
The second object is a plain NumPy array. It is not part of the Series, so you must unpack it when you call the function.
Edges from an integer bin count
With an integer bins, pd.cut splits the range from minimum to maximum into equal-width pieces.
import pandas as pd
values = pd.Series([1, 5, 12, 20, 33, 50])
binned, edges = pd.cut(values, bins=3, retbins=True)
print(edges.round(3))
print(binned.cat.categories)The range is 49, so each bin is about 16.33 wide. Pandas needs four edges to make three bins. The edges are roughly 0.951, 17.333, 33.667 and 50.
The first edge is 0.951, not 1. When intervals are closed on the right, the lowest interval would otherwise exclude the minimum. To prevent that, pandas moves the first edge down by 0.1% of the range (0.049 here). With right=False, the same adjustment moves the last edge up instead.
This is a case where retbins pays off. If you computed np.linspace(1, 50, 4) by hand, you would get a first edge of exactly 1 and lose the minimum value from the first bin. The array from retbins is the one that matches what pd.cut actually used.
Edges from quantiles
With pd.qcut, the edges are quantiles of the data.
import pandas as pd
scores = pd.Series(range(1, 101))
quartiles, edges = pd.qcut(scores, q=4, retbins=True)
print(edges)
print(quartiles.value_counts().sort_index())The edges are 1, 25.75, 50.5, 75.25 and 100. These are the minimum, the three quartiles, and the maximum. The quartiles use linear interpolation, which is why you see 25.75 and not a value that appears in the data. Each of the four bins holds 25 rows.
Notice that the array has q + 1 entries. This rule holds for any number of bins: n bins always need n + 1 edges.
If you pass quantile fractions instead of an integer, the same rule applies, because the fractions are the positions of the edges:
import pandas as pd
scores = pd.Series(range(1, 101))
groups, edges = pd.qcut(scores, q=[0, 0.1, 0.9, 1.0], retbins=True)
print(edges)The edges are the 0th, 10th, 90th and 100th percentiles, so the array is [1, 10.9, 90.1, 100]. The middle bin holds the central 80% of the rows.
Explicit edges come back unchanged
If you pass your own list of edges, the second return value is that list as an array. This is mostly useful for consistency, because code that handles all three cases can treat the result the same way.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups, edges = pd.cut(ages, bins=[0, 18, 65, 120], retbins=True)
print(edges)The printed array is [ 0 18 65 120]. Because you supplied these numbers, nothing is learned here. The value of retbins comes from the computed cases above.
Seeing what duplicates='drop' removed
When a column has many repeated values, several quantile edges can be equal. pd.qcut raises a ValueError by default. Setting duplicates="drop" removes the repeated edges and gives you fewer bins than you asked for. The edges array is the clearest way to see what happened.
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("requested bins:", 4)
print("actual bins:", len(edges) - 1)
print(edges)The four quartile cut points are 1, 1, 1, 2.25 and 4, so the repeated 1s collapse. The edges become [1, 2.25, 4], which gives 2 bins.
Check len(edges) - 1 whenever you use duplicates="drop" together with labels. If you pass four labels and pandas produces only two bins, you get a ValueError about the number of labels. Counting the edges first tells you how many labels you need.
Reusing the edges on new data
The most practical use of retbins is applying the same bins to data that was not part of the original computation. Examples are a test set, next month's records, or a single new row. You fit the edges on one dataset, then pass the array to pd.cut.
import numpy as np
import pandas as pd
train = pd.Series(range(1, 101))
_, edges = pd.qcut(train, q=4, retbins=True)
new = pd.Series([0, 10, 30, 60, 80, 150])
print(pd.cut(new, bins=edges, include_lowest=True))The result has NaN for 0 and 150, because both lie outside the range 1 to 100. The include_lowest=True argument is needed because the first edge is exactly the training minimum, and without it the value 1 would also fall outside the first interval. (pd.qcut does this internally, which is why the training data was fully covered.)
To make the bins accept any value, replace the outer edges with infinity and pass labels:
import numpy as np
import pandas as pd
train = pd.Series(range(1, 101))
_, edges = pd.qcut(train, q=4, retbins=True)
open_edges = edges.copy()
open_edges[0] = -np.inf
open_edges[-1] = np.inf
new = pd.Series([0, 10, 30, 60, 80, 150])
labels = ["Q1", "Q2", "Q3", "Q4"]
print(pd.cut(new, bins=open_edges, labels=labels))Now 0 and 10 land in Q1, 30 in Q2, 60 in Q3, and 80 and 150 in Q4. Nothing is NaN.
Common mistakes
- Forgetting to unpack.
result = pd.cut(values, bins=3, retbins=True)gives you a tuple. Calling.value_counts()on it raises anAttributeError. Writebinned, edges = .... - Editing the array in place. The edges array is an ordinary NumPy array. If you assign into it, as with
edges[0] = -np.inf, the change affects every other name that points to it. Useedges.copy()when you want to keep the original. - Rebuilding edges from printed intervals. Interval labels such as
(25.75, 50.5]round to 3 significant decimals by default. Retyping them can shift a boundary slightly, so a value that sat exactly on an edge may land in a different bin. Use the array fromretbinsinstead. - Reusing edges without
include_lowest=True. Edges frompd.qcutstart at the data minimum, so the minimum itself needsinclude_lowest=Truewhen you pass the edges topd.cut. - Assuming
qbins. Withduplicates="drop", the number of bins islen(edges) - 1, which can be smaller thanq.
Exercise
Exercise
Given values = pd.Series([10, 20, 30, 40, 50]), you call binned, edges = pd.qcut(values, q=[0, 0.5, 1], retbins=True). What does edges contain, and how many values fall in each bin?
Show answer
The edges are [10, 30, 50]. These are the minimum, the median (the 0.5 quantile), and the maximum. The first bin holds 10, 20 and 30 (3 values), because qcut includes the lowest edge and intervals are closed on the right. The second bin holds 40 and 50 (2 values).