Sub topic 6
Giving bins readable labels
This chapter assumes you can call pd.cut with explicit edges and know that intervals are closed on the right by default. It covers how the labels argument names the bins and what the labelled result looks like.
Why labels matter
Without labels, pd.cut names each bin with an interval such as (18, 65]. That is exact, but it is awkward in reports and charts. The labels argument replaces those intervals with names you choose.
Passing a list of labels
Give labels one name per bin. Four edges make three bins, so you need three labels.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
bins = [0, 18, 65, 120]
labels = ["child", "adult", "senior"]
groups = pd.cut(ages, bins=bins, labels=labels)
print(groups)
print(groups.dtype)The result has the dtype category. The labels are its categories, and they keep the order you listed them in. Labelling a bin does not change which values fall into it. Only the displayed name changes.
If the label count is wrong, pandas raises a ValueError.
import pandas as pd
ages = pd.Series([3, 17, 25])
try:
pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult"])
except ValueError as err:
print("ValueError: label count must be one fewer than the edge count")Labels are ordered
When you pass a list of labels, pd.cut returns an ordered categorical. The order follows the label list, not alphabetical order. Two things follow from this:
- Sorting and
groupbyoutput use the label order, sochildcomes beforeadultandsenior. - Comparisons work, so you can filter on a threshold.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups >= "adult")
print(ages[groups >= "adult"].tolist())Integer codes with labels=False
Set labels=False to get the bin position as an integer, starting at 0. This is compact, and it suits code that needs numbers, such as a model feature.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
codes = pd.cut(ages, bins=[0, 18, 65, 120], labels=False)
print(codes.tolist())The codes are [0, 0, 1, 1, 2, 2]. If a value falls outside every bin, the result for it is NaN. In that case the integer codes come back as floats.
Building labels from the edges
For many bins, typing labels by hand invites mistakes. Generate them from the edges so they cannot drift out of sync.
import pandas as pd
bins = [0, 20, 50, 100]
labels = [f"{lo}-{hi}" for lo, hi in zip(bins[:-1], bins[1:])]
print(labels)
prices = pd.Series([5, 20, 21, 50, 99])
print(pd.cut(prices, bins=bins, labels=labels).tolist())The labels are ['0-20', '20-50', '50-100']. A price of 20 lands in 0-20, because the bins are closed on the right.
Choosing a labelling approach
| Goal | Setting | Result |
|---|---|---|
| Show exact ranges | `labels` omitted | Interval categories such as `(0, 18]` |
| Show readable names | `labels=[...]` | Ordered categorical with your names |
| Get bin positions | `labels=False` | Integers starting at 0 |
Exercise
You call pd.cut(scores, bins=[0, 50, 80, 100], labels=["low", "mid", "high"]). A score of 80 is in the data. Which label does it get, and what happens if you pass only two labels?
Show answer
A score of 80 gets "mid", because bins are closed on the right by default, so the second bin is (50, 80]. Passing only two labels raises a ValueError, because three bins need three labels (one fewer than the four edges).