ANALYSIS TOOL BOX

Data Processing

CreateBinnedColumn

Discretize continuous numeric data into discrete bins using specified strategies.

data-processingcleaningtransformationwrangling

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.

Teaching Note

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

ParameterTypeDefaultDescription
dataframerequiredA pandas DataFrame containing high-cardinality numeric data.
numeric_column_namerequiredThe name of the column containing the continuous numeric values to be binned.
number_of_bins6The 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_nameNoneThe 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

python
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