Discretization

Discretization is the process of converting a continuous numeric variable into a set of discrete categories or bins - useful for simplifying data and for algorithms that work better with categorical inputs.

Why Discretize

# Converts:
Age = [22, 25, 31, 45, 52, 60]

# Into:
AgeGroup = ["Young", "Young", "Middle", "Middle", "Senior", "Senior"]

Common Discretization Methods

Equal-Width Binning:     Divides the range into bins of equal size
Equal-Frequency Binning: Divides data so each bin has roughly the same number of points
Custom Binning:          Uses domain knowledge to define meaningful bin edges

Implementing in Python

import pandas as pd

df = pd.DataFrame({
    "Age": [22, 25, 31, 45, 52, 60, 65, 70]
})

df["AgeGroup"] = pd.cut(
    df["Age"],
    bins=[0, 30, 50, 100],
    labels=["Young", "Middle", "Senior"]
)

print(df)

When to Use Discretization

Discretization can make patterns easier to interpret, reduce the effect of noise or outliers, and is sometimes required by algorithms that assume categorical inputs rather than continuous ones.

Choosing bin boundaries carelessly can lose valuable information - always check whether the resulting categories still make sense for the problem at hand.

Coming Up Next

Next, you'll learn about Entropy, a key concept behind how Decision Trees decide where to split.

Equal-Width vs Equal-Frequency in Code

Pandas offers two functions that match the two most common methods. pd.cut splits the value range into equal-sized intervals, while pd.qcut splits the data so each bin gets roughly the same number of rows.

import pandas as pd

income = pd.Series([18, 22, 25, 27, 30, 35, 40, 48, 60, 250])  # in thousands

equal_width = pd.cut(income, bins=3)
equal_freq  = pd.qcut(income, q=3, labels=["Low", "Mid", "High"])

print(equal_width.value_counts().sort_index())
print(equal_freq.value_counts())

With equal-width bins, the single large value of 250 stretches the range, so nine of the ten people fall into the first bin and the other two bins are almost empty. Equal-frequency bins spread the people out evenly, which usually suits skewed data such as income, house prices or website visits.

Doing It Safely in a Machine Learning Pipeline

Bin edges are learned from data, so they must be learned from training data only. If you calculate quantiles on the full dataset before splitting, information from the test set leaks into training and your evaluation becomes too optimistic. Scikit-learn's KBinsDiscretizer follows the usual fit-then-transform pattern that prevents this.

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import KBinsDiscretizer

X = df[["Age"]]
X_train, X_test = train_test_split(X, test_size=0.25, random_state=42)

kb = KBinsDiscretizer(n_bins=4, encode="ordinal", strategy="quantile")
X_train_binned = kb.fit_transform(X_train)   # learns edges from training rows
X_test_binned  = kb.transform(X_test)        # reuses the same edges

print(kb.bin_edges_)

The strategy parameter accepts "uniform" (equal width), "quantile" (equal frequency) and "kmeans" (edges based on clusters). Setting encode="onehot" instead produces one column per bin, which suits linear models.

Supervised discretization

The methods above ignore the target variable. Supervised methods choose edges that best separate the target classes. A simple approach is to fit a shallow decision tree on one feature and use its split points as bin edges. This often produces fewer, more meaningful bins.

Edge Details That Trip People Up

  • Interval boundaries. pd.cut uses right-closed bins by default, so with edges at 30 and 50, the value 30 falls in the first bin. Use right=False if you want 30 to start the second bin.
  • The lowest value. If a value equals the first edge exactly, it is excluded unless you pass include_lowest=True, and it becomes NaN.
  • Repeated values with qcut. When many rows share the same value, quantile edges can collide and raise an error. Pass duplicates="drop" or choose fewer bins.
  • Values outside training range. New data larger than every training value must still land in a bin; check how your tool handles it.

When Not to Discretize

Tree-based models such as random forests and gradient boosting already find their own split points, so manual binning rarely helps them and can remove useful detail. Binning also hides differences inside a bin: ages 31 and 49 look identical in a "Middle" group. Use it when interpretation, rules, or a model's requirements call for categories, and compare model scores with and without it before deciding.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course