Sub topic 12
Turning numbers into categories with cut and qcut
This chapter assumes you can build a DataFrame, select a column by name, and know that np.select can label rows by condition. Binning is the same idea with less code: you give pandas the edges of the groups and it labels every value for you.
Fixed edges with pd.cut
pd.cut assigns each value to an interval whose edges you choose. Intervals include the right edge by default, so (0, 5] contains 5 but not 0.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp", "desk"],
"price": [1.5, 12.0, 30.0, 5.0],
})
df["price_band"] = pd.cut(
df["price"],
bins=[0, 5, 20, float("inf")],
labels=["low", "mid", "high"],
)
print(df)The price 5.0 lands in low because the right edge is closed. Pass right=False to close the left edge instead, which makes the intervals [0, 5).
Without labels, pandas uses the interval itself as the label, such as (5.0, 20.0]. That is useful for checking your edges before you rename the groups.
Equal-sized groups with pd.qcut
pd.qcut picks the edges for you so that each group holds about the same number of rows. You pass the number of groups, or a list of quantiles.
scores = pd.Series([3, 8, 12, 15, 22, 40, 41, 90])
quartiles = pd.qcut(scores, q=4, labels=["Q1", "Q2", "Q3", "Q4"])
print(quartiles.value_counts().sort_index())Each quartile gets two of the eight values. Use cut when the boundaries have meaning, such as price tiers or age groups. Use qcut when you want ranks, such as top 25 percent.
| Function | You provide | Group sizes |
|---|---|---|
| `pd.cut` | Bin edges or a bin count | Uneven |
| `pd.qcut` | Number of quantiles | About equal |
Common errors
- Values outside the edges become NaN. With
bins=[0, 5, 20], a price of 30 or 0 gets no label. Usefloat("inf")as the last edge, or start below your minimum. - Label count mismatch. You need exactly one label per interval, which is one fewer than the number of edges. Otherwise pandas raises a
ValueError. - Duplicate quantile edges. If many values are identical,
qcutmay fail with "Bin edges must be unique". Passduplicates="drop", but then you get fewer groups than requested, so fewer labels must be supplied. - Missing values stay missing. NaN in the input gives NaN in the output. Neither function fills them in.
Exercise
A Series holds ages [4, 17, 18, 35, 64, 65]. Write a pd.cut call that labels ages up to 17 as "minor", 18 to 64 as "adult", and 65 and over as "senior". Which edges and which setting of right do you use?
Show answer
Use bins=[0, 17, 64, float("inf")] with labels=["minor", "adult", "senior"], keeping the default right=True. Age 17 falls in (0, 17], 18 and 64 fall in (17, 64], and 65 falls in (64, inf]. An equivalent choice is right=False with bins=[0, 18, 65, float("inf")].