Sub topic 1
Why and when to bin numeric data
Binning (also called discretization) replaces a continuous number with the name of the range it falls into. An age of 42 becomes "adult", and a price of 18.50 becomes "low". Pandas provides two functions for this, pd.cut and pd.qcut, and later chapters cover them in detail. This chapter explains when binning is the right tool and what it costs you, so that you choose it deliberately.
Prerequisites
This chapter assumes you can:
- Write basic Python, including lists and function calls with keyword arguments.
- Create a pandas
SeriesandDataFrameand select columns from them. - Read basic descriptive statistics: minimum, maximum, median, and percentiles.
You do not need to know pd.cut or pd.qcut yet. The short examples below use pd.cut only to show what binning does.
What binning does
A numeric column can hold millions of distinct values. Binning maps each value to one of a small number of groups. The result is a categorical column: a column that holds a fixed set of labels instead of arbitrary numbers.
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)The three edge intervals are (0, 18], (18, 65] and (65, 120]. Each row now carries one of three labels: 3 and 17 are child, 25 and 42 are adult, and 67 and 90 are senior. The original number is gone from this column, so keep the source column if you may need it later.
Reasons to bin
Binning is worth doing when the group matters more than the exact value. These are the common cases.
The domain already defines the groups
Many fields have agreed thresholds. Examples are age brackets in a survey, income tax bands, body mass index categories, and credit score tiers. Your analysis should use the same cut points as the people who read your report. Here the bin edges come from the domain, not from the data.
You want a readable summary
A table with 5 rows is easier to read than a histogram of 500 distinct values. Binning lets you report "average order value by price band" instead of listing every price. It also makes charts with categorical axes possible, such as bar charts of counts per band.
The relationship with the target is not a straight line
Linear models fit one slope across the whole range of a feature. If the real effect is U-shaped, or flat and then steep, one slope fits badly. Binning lets each range have its own effect. The example below shows how a group summary exposes an uneven pattern.
import pandas as pd
df = pd.DataFrame({
"age": [22, 25, 31, 38, 44, 52, 61, 68, 72, 80],
"visits": [2, 3, 1, 1, 2, 4, 6, 9, 11, 10],
})
df["band"] = pd.cut(
df["age"],
bins=[0, 40, 65, 120],
labels=["young", "middle", "older"],
)
summary = df.groupby("band", observed=True)["visits"].agg(["count", "mean"])
print(summary)The mean number of visits is 1.75 for young (4 rows), 4.0 for middle (3 rows) and 10.0 for older (3 rows). The jump between groups is much larger than the step inside any one group. Grouping makes that visible at a glance.
Outliers dominate the scale
A few extreme values can stretch a numeric axis and distort averages. Quantile-based bins ignore how far away an extreme value is. They only record that it belongs to the top group. This makes the feature less sensitive to outliers, though it also discards the information that the value was extreme.
The consumer needs categories
Some tools want categorical input: a naive Bayes classifier, a cross-tabulation, a contingency table for a chi-squared test, or a dashboard filter. Binning produces that input directly.
Reasons not to bin
Binning is lossy. You should be able to name what you gain before you accept these costs.
| Cost | What happens |
|---|---|
| Information loss | Values 3 and 17 become the same `child`. Differences inside a bin disappear. |
| Cliff effects | Two nearly identical values on opposite sides of an edge get different labels. |
| Arbitrary edges | Different cut points can lead to different conclusions from the same data. |
| Less statistical power | Models and tests with binned predictors usually detect effects less well than with the raw number. |
| Extra columns | A model that one-hot encodes bins gains a column per bin. |
The cliff effect is easy to see. The edges below put 18 in child and 19 in adult, although the two ages differ by one year.
import pandas as pd
ages = pd.Series([17, 18, 19, 64, 65, 66])
groups = pd.cut(
ages,
bins=[0, 18, 65, 120],
labels=["child", "adult", "senior"],
)
print(groups.tolist())This prints ['child', 'child', 'adult', 'adult', 'adult', 'senior']. Ages 18 and 19 are one year apart yet land in different groups, while 19 and 64 are 45 years apart and share one.
Note that 18 is child and 65 is adult. Intervals are closed on the right by default, so the upper edge belongs to the lower bin. The chapter on interval closure covers this and how to change it.
Models that do not need binning
Some model families already split numeric features on thresholds. Decision trees, random forests, and gradient boosted trees search for the best cut points themselves. Hand-made bins rarely help these models and can hide a better split. Binning is more useful for linear and logistic regression, for hand-built reports, and for simple categorical models.
Fixed edges or data-driven edges
Once you decide to bin, the next question is where the edges come from. Pandas offers two approaches, and the rest of this tutorial develops both.
pd.cutuses edges you choose, or equal-width ranges. The bins differ in how many rows they hold.pd.qcutuses quantiles of the data. The bins hold roughly the same number of rows but differ in width.
A short rule of thumb: if meaningful thresholds exist, use cut with those edges. If you want to compare equally sized groups such as quartiles, use qcut. The chapter on choosing between the two gives a fuller comparison.
A quick check before you bin
Look at the data before you choose edges. These steps take a few lines and prevent most bad bins.
- Print
describe()to see the minimum, maximum, and quartiles. - Check for missing values with
isna().sum(). Missing numbers stay missing after binning and appear asNaN. - Confirm that every value falls inside your outer edges. A value outside them also becomes
NaN. - Check how many rows land in each bin. A bin with two rows rarely supports a conclusion.
import pandas as pd
prices = pd.Series([5, 12, 18, 25, 40, 55, 70, 95])
print(prices.describe())
print("missing:", prices.isna().sum())
print("range:", prices.min(), "to", prices.max())Here the minimum is 5 and the maximum is 95, so outer edges of 0 and 100 would cover every value. Later chapters show what happens when they do not.
Summary of the decision
Bin when groups are what you need to communicate, when the domain supplies thresholds, or when a simple model must capture a non-linear effect. Keep the raw numbers when the downstream model can split by itself, or when the precision of the value matters. Store bins in a new column, and inspect the data first.
Exercise
A data analyst has a column of customer ages and wants to train a gradient boosted tree model to predict churn. A colleague suggests replacing age with the bins child, adult and senior first. Give one reason this may not help and one situation in which binning age would still be worthwhile.
Show answer
Tree models already search for the best age thresholds themselves, so fixed bins can hide a better split and throw away detail, which usually helps little or hurts. Binning age is still worthwhile when the output is a report that must use agreed brackets, such as a churn rate per age band for a business audience, or when a simple model or cross-tabulation needs categorical input. In both cases keep the raw age column and add the bins as a new column.