Sub topic 6
Giving bins readable labels
This chapter covers the labels argument of pd.cut and pd.qcut. It assumes you can call both functions with explicit edges or a quantile count. It also assumes you know what the closed side of an interval means. If either is unfamiliar, review the earlier chapters on explicit edges and interval closure first.
Why labels matter
Without labels, a binned column holds Interval objects such as (18, 65]. These are exact, but they are awkward in charts, reports and group-by output. A label such as "adult" is easier to read, and you choose it yourself.
The labels argument accepts three kinds of value:
| Value | Result |
|---|---|
| Omitted or `None` | Intervals such as `(18, 65]` become the categories. |
| A list or array of names | Each bin gets the name at the same position. |
| `False` | No categories. You get integer bin numbers starting at 0. |
Passing a list of labels
The list must contain exactly one label per bin. Bins sit between edges, so the list is one item shorter than bins.
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.name)
print(groups.cat.ordered)Labels are matched to bins by position, from the lowest bin to the highest. The first label goes with (0, 18], the second with (18, 65], and so on. The labels do not need to be sorted alphabetically or in any particular way.
The dtype is category, and groups.cat.ordered is True. Ordering follows the order of the list you supplied.
A wrong number of labels fails loudly
If the label count does not match the bin count, pandas raises a ValueError.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
bins = [0, 18, 65, 120]
try:
pd.cut(ages, bins=bins, labels=["child", "adult"])
except ValueError as err:
print(err)The message says the bin labels must be one fewer than the number of bin edges. A common cause is counting the edges instead of the bins. When you pass an integer such as bins=4, you get four bins, so you need four labels.
Labels do not change which bin a value falls into
Labels are only names. Interval closure still decides membership. With the default right=True, the age 18 belongs to "child" because the first bin is (0, 18].
This matters when you generate labels from the edges. A label like "18-65" suggests that 18 is included, but with the default closure it is not.
import pandas as pd
ages = pd.Series([18, 19, 65, 66])
bins = [0, 18, 65, 120]
labels = [f"{lo}-{hi}" for lo, hi in zip(bins[:-1], bins[1:])]
print(labels)
print(pd.cut(ages, bins=bins, labels=labels))The labels come out as "0-18", "18-65" and "65-120". The values 18 and 65 land in "0-18" and "18-65", the bins whose upper edge they match. Generating labels in a list comprehension keeps them in sync with the edges when you change the edges later. It does not tell readers which side is open.
Integer codes with labels=False
When you only need a group number, set labels=False. The result is a plain integer array instead of a categorical.
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())
print(codes.dtype)The codes are [0, 0, 1, 1, 2, 2] and the dtype is int64. Codes are compact and fast to compare. They are also useful as input to code that expects numbers, such as a lookup into an array of per-bin parameters. The cost is that the output no longer says what each number means. Keep the edges somewhere you can find them.
If the input contains values outside the bins or missing values, those positions have no code. In that case the result becomes a float array with NaN, so the dtype is not guaranteed to be an integer type. The chapter on NaN results covers this.
The ordered flag
When you pass a list of labels, the resulting categorical is ordered by default. An ordered categorical supports comparisons and sorts by category position, not alphabetically.
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(groups.sort_values().tolist())
print(groups.max())Alphabetically, "adult" would sort before "child". Here the sort gives child, child, adult, adult, senior, senior, and max() returns "senior". The comparison groups >= "adult" is True for every row that is not a child. The string must be one of the categories, or pandas raises an error.
Duplicate labels
You might want two bins to share one name, for example to merge a low and a high tail into "extreme". An ordered categorical cannot have repeated categories, so you must turn ordering off.
import pandas as pd
temps = pd.Series([-20, 5, 18, 30, 45])
bins = [-50, -10, 10, 25, 50]
labels = ["extreme", "cool", "mild", "extreme"]
grouped = pd.cut(temps, bins=bins, labels=labels, ordered=False)
print(grouped.tolist())
print(grouped.cat.categories.tolist())With ordered=False, pandas accepts the repeated label and collapses it into one category. The result has three categories, and -20 and 45 both become "extreme". If you leave ordered at its default while passing duplicate labels, pandas raises a ValueError that tells you to pass ordered=False. The ordered argument exists in current pandas releases but not in very old ones, so check your version if you see an unexpected-keyword error.
Labels with qcut
pd.qcut takes the same labels argument with the same rules. The label count must equal the number of bins, which is q for an integer or one less than the number of fractions for a list.
import pandas as pd
scores = pd.Series(range(1, 101))
tiers = pd.qcut(scores, q=[0, 0.5, 0.9, 1.0], labels=["bottom half", "next 40%", "top 10%"])
print(tiers.value_counts().sort_index())Here the fractions give three bins, so there are three labels. The counts are 50, 40 and 10. The labels describe the share of rows rather than a value range, which is usually the point of qcut. Because labels hide the numeric edges, add retbins=True when you need to record where the cut points fell.
Empty categories stay
A category that matches no rows still exists in the result. This is a property of categoricals, and it affects counts.
import pandas as pd
ages = pd.Series([3, 17, 25, 42])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts())
print(groups.cat.categories.tolist())value_counts reports senior with a count of 0 rather than omitting it. This is often what you want in a report, because the table has the same rows every time. In a groupby, the observed=True argument removes such empty groups.
Changing labels after binning
You can relabel an existing result without binning again. Use rename_categories with a dictionary, or with a list of the same length.
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"])
renamed = groups.cat.rename_categories({"child": "minor", "senior": "retired"})
print(renamed.cat.categories.tolist())The categories become ["minor", "adult", "retired"] and the order is unchanged. This is handy when you bin once for analysis and then relabel for a different audience.
Choosing a labeling approach
Use these rules in practice:
- Leave
labelsunset while exploring, so you can see the exact intervals. - Pass a list of unique names for reports, charts and group-by tables.
- Use
labels=Falsewhen the next step is numeric. - Use
ordered=Falseonly when you need repeated names, and accept that comparisons are then unavailable.
Exercise
You run pd.cut(prices, bins=[0, 20, 50, 100], labels=["low", "mid", "high", "premium"]). What happens, and how do you fix it? Then explain why a list of three labels with bins=[0, 20, 50, 100] would still not guarantee that the price 20 is labeled "mid".
Show answer
pandas raises a ValueError because the three bins need exactly three labels, and four were supplied. Remove "premium", or add a fourth bin by adding an edge such as 200. Labels never decide membership. With the default right=True, the bin (0, 20] includes 20, so the price 20 is labeled "low". To label 20 as "mid", pass right=False, which makes the bins [0, 20), [20, 50) and [50, 100).
Exercise
Write code that bins temps = pd.Series([-20, 5, 18, 30, 45]) with bins=[-50, -10, 10, 25, 50] so that the lowest and highest bins both get the label "extreme", the other two get "cool" and "mild", and the result can be created without an error.
Show answer
Use pd.cut(temps, bins=[-50, -10, 10, 25, 50], labels=["extreme", "cool", "mild", "extreme"], ordered=False). Repeated labels are rejected for an ordered categorical, so ordered=False is required. The result has the categories "extreme", "cool" and "mild", and -20 and 45 are both "extreme".