Introduction
A continuous variable — age, income, session duration — is sometimes more useful as a
handful of meaningful groups than as raw numbers, whether you're feeding it to an
algorithm that wants categorical input or building a readable chart.
CreateBinnedColumn answers "how do I split this continuous variable into bins that
reflect its actual structure, not arbitrary cutoffs?" by supporting equal-width,
equal-frequency, or k-means-based binning strategies. Reach for it when the analytic
question is about segments or ranges rather than exact values — customer tiers, age
brackets, or natural clusters within a single variable.
The function is particularly useful for:
- Feature engineering for machine learning models (e.g., decision trees, naïve bayes)
- Segmenting customers into groups (e.g., age groups, income brackets)
- Reducing noise and handling outliers in continuous data
- Creating histograms or grouped summaries for exploratory data analysis
- Simplifying the interpretation of complex numeric distributions
- Identifying natural clusters within a single dimension using k-means
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
dataframerequired | | — | A pandas DataFrame containing high-cardinality numeric data. |
numeric_column_namerequired | | — | The name of the column containing the continuous numeric values to be binned. |
number_of_bins | | 6 | The number of bins to create. |
binning_strategy | | 'kmeans' | The strategy used to define bin widths: 'uniform' (identical widths), 'quantile' (equal number of points per bin), or 'kmeans' (values grouped by nearest 1D k-means cluster center). |
new_column_name | | None | The name of the new column to be added to the DataFrame. If None, the column will be named '{numeric_column_name}- Binned'. |
Returns
An updated DataFrame containing the original columns plus a new column with ordinal bin identifiers (labeled 0, 1, 2, ...).
Example
from analysistoolbox.data_processing import CreateBinnedColumn
import pandas as pd
# Create age groups using k-means clustering
demographics = pd.DataFrame({
'user_id': range(1, 7),
'age': [18, 22, 35, 42, 58, 65]
})
demographics = CreateBinnedColumn(
demographics,
numeric_column_name='age',
number_of_bins=3
)
# Adds 'age- Binned' column with values 0, 1, or 2