Introduction
How many distinct groups exist in a population of customers, products, or locations, and which observations belong to which group? CreateKMeansClusters answers this with K-Means, a centroid-based algorithm that partitions data into K non-overlapping clusters by minimizing within-cluster variance. When you don't know K in advance, the function runs the elbow method automatically — plotting distortion against candidate cluster counts and picking the point where adding more clusters stops paying off — so you get a defensible starting segmentation without manual trial and error.
K-Means clustering is essential for:
- Customer segmentation and behavioral grouping
- Market basket analysis and product categorization
- Image compression and color quantization
- Document clustering and topic grouping
- Anomaly detection through distance from centroids
- Data preprocessing for supervised learning
- Geographic clustering and location-based analysis
- Performance optimization through data summarization
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
dataframerequired | | — | A pandas DataFrame containing the data to cluster. Rows with missing values in clustering columns will be excluded from the analysis. |
list_of_value_columns_for_clustering | | None | List of numeric column names to use as features for clustering. If None, all numeric columns in the DataFrame will be automatically selected. Defaults to None. |
number_of_clusters | | None | Number of clusters (K) to create. If None, uses the elbow method to automatically determine the optimal number between 2 and 20 (or number of observations, whichever is smaller). Defaults to None. |
column_name_for_clusters | | 'K-Means Cluster' | Name for the new column containing cluster assignments (as strings). Defaults to 'K-Means Cluster'. |
random_seed | | 412 | Random seed for reproducibility of centroid initialization. K-Means uses random initialization, so setting this ensures consistent results. Defaults to 412. |
maximum_iterations | | 300 | Maximum number of iterations for the K-Means algorithm to converge. Increase if convergence warnings appear. Defaults to 300. |
scale_clustering_column_values | | True | Whether to standardize features to zero mean and unit variance before clustering. Highly recommended for K-Means when features have different scales. Defaults to True. |
print_peak_to_peak_range_of_each_column | | False | Whether to print the peak-to-peak range of each clustering variable, useful for assessing scale differences before standardization. Defaults to False. |
show_cluster_summary_plots | | True | Whether to generate kernel density plots for each clustering variable, showing the distribution of values within each cluster. Defaults to True. |
color_palette | | 'Set2' | Seaborn color palette name for cluster visualization. Options include 'Set1', 'Set2', 'Set3', 'Pastel1', 'Dark2', etc. Defaults to 'Set2'. |
caption_for_plot | | None | Optional caption text to display below each density plot. Defaults to None. |
data_source_for_plot | | None | Optional data source attribution text, appended to caption. Defaults to None. |
show_y_axis | | False | Whether to display the y-axis (density scale) on summary plots. Defaults to False. |
title_y_indent | | 1.1 | Vertical position for plot titles relative to axes. Defaults to 1.1. |
subtitle_y_indent | | 1.05 | Vertical position for plot subtitles relative to axes. Defaults to 1.05. |
caption_y_indent | | -0.15 | Vertical position for plot captions relative to axes. Defaults to -0.15. |
summary_plot_size | | (6, 4) | Figure size for each summary density plot as a tuple of (width, height) in inches. Defaults to (6, 4). |
Returns
A pandas DataFrame — the original data with one additional column containing cluster assignments as string labels (e.g., '0', '1', '2'). Rows with missing values in clustering columns are excluded and will have NaN in the cluster column.
Example
from analysistoolbox.descriptive_analytics import CreateKMeansClusters
import pandas as pd
# Customer segmentation with automatic elbow method
customer_df = pd.DataFrame({
'customer_id': range(1, 301),
'annual_revenue': [1000 + i * 100 for i in range(300)],
'purchase_frequency': [2 + i % 50 for i in range(300)],
'avg_transaction_value': [50 + i % 200 for i in range(300)]
})
segmented_df = CreateKMeansClusters(
customer_df,
list_of_value_columns_for_clustering=['annual_revenue', 'purchase_frequency', 'avg_transaction_value'],
scale_clustering_column_values=True,
show_cluster_summary_plots=True
)
# Automatically determines optimal K using the elbow method, shows density plots