Sub topic 8
Turning numbers into categories with cut and qcut
This chapter assumes you can create a pandas Series, read basic dtypes, and use value_counts. It also assumes you know that a categorical stores categories plus integer codes. Here you will turn a numeric column into a categorical column. This is called binning.
Two functions, two ways to choose edges
pd.cutuses edges you choose, or equal-width bins. Use it when the boundaries mean something, such as age groups or tax brackets.pd.qcutuses quantiles, so each bin holds about the same number of rows. Use it for ranks such as quartiles or deciles.
Both return a categorical. If you pass labels, the categories are those labels. If you don't, they are Interval objects.
Fixed edges with cut
import pandas as pd
ages = pd.Series([5, 17, 18, 30, 64, 80])
bins = [0, 18, 65, 120]
names = ["child", "adult", "senior"]
right = pd.cut(ages, bins=bins, labels=names)
left = pd.cut(ages, bins=bins, labels=names, right=False)
print(right.tolist()) # ['child', 'child', 'child', 'adult', 'adult', 'senior']
print(left.tolist()) # ['child', 'child', 'adult', 'adult', 'adult', 'senior']
print(right.dtype, right.cat.ordered)By default the bins are right-inclusive, so they are (0, 18], (18, 65] and (65, 120]. The age 18 is a child. With right=False the bins are [0, 18), [18, 65) and [65, 120), so 18 becomes an adult. Most off-by-one errors in binning come from this setting.
cut returns an ordered categorical. The labels follow the order of the bins, so child < adult < senior works without extra setup.
Three more points:
- You need one more edge than you have labels.
- A value outside every bin becomes
NaN. For example, an age of 130 with the bins above givesNaN. - The lowest edge is excluded unless you pass
include_lowest=True. A value of exactly 0 would otherwise becomeNaN.
You can also pass an integer, such as bins=4. Pandas then splits the range from the minimum to the maximum into four equal-width bins.
Equal-sized groups with qcut
import pandas as pd
values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])
quartiles = pd.qcut(values, q=4, labels=["q1", "q2", "q3", "q4"])
print(quartiles.tolist())
print(quartiles.value_counts().sort_index())The quartile edges here are 1, 2.75, 4.5, 6.25 and 8. Each label ends up with two rows. Unlike cut, qcut includes the lowest value in the first bin by default.
You can pass a list of quantiles instead of a count, for example q=[0, 0.1, 0.9, 1]. That gives a bottom 10%, a middle 80% and a top 10%.
Repeated values break quantile edges
If many rows share one value, several quantiles can land on the same number. The edges are then not unique, and qcut raises a ValueError.
import pandas as pd
s = pd.Series([1, 1, 1, 1, 2, 3])
codes = pd.qcut(s, q=4, labels=False, duplicates="drop")
print(codes.tolist()) # [0, 0, 0, 0, 1, 1]duplicates="drop" removes the repeated edges, so you get fewer bins than you asked for. That is why this example returns integer codes with labels=False. A list of labels must match the final number of bins, which you can't know before the edges are dropped.
Empty bins stay
Binned results keep every category, even when no row falls in it.
import pandas as pd
scores = pd.Series([10, 20, 95])
grades = pd.cut(scores, bins=[0, 50, 80, 100], labels=["low", "mid", "high"])
print(grades.value_counts())The output lists mid with a count of 0. This is useful for reports with a fixed layout. It also leads into the next chapter, where groupby on a categorical key shows the same behavior.
Inspecting the bins
To see the actual edges, pass retbins=True. The function then returns the result and the edges as a tuple.
import pandas as pd
result, edges = pd.qcut(pd.Series(range(100)), q=4, retbins=True)
print(edges) # [ 0. 24.75 49.5 74.25 99. ]Save the edges from training data and reuse them with pd.cut on new data. If you call qcut again on new data, the quantiles shift and the groups no longer match.
Exercise
A column contains the values 0, 10, 20, 30. You call pd.cut(col, bins=[0, 10, 30]) with no other arguments. What happens to the value 0, and which option fixes it?
Show answer
The value 0 becomes NaN, because the first bin is (0, 10] and excludes its left edge. Passing include_lowest=True puts 0 in the first bin. Setting right=False would also include 0, but it would move 10 into the second bin.