
π This article includes 1 downloadable practice file β
You have a sheet of customers with orders, total spend and days since the last purchase. Which customers are alike? K-means finds groups without you defining them first β an example of unsupervised learning.
# pip install pandas openpyxl scikit-learn
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
df = pd.read_excel("customers.xlsx") # columns: Customer, Orders, Spend, DaysSinceLast
features = ["Orders", "Spend", "DaysSinceLast"]
X = StandardScaler().fit_transform(df[features])
df["Segment"] = KMeans(n_clusters=4, n_init=10, random_state=0).fit_predict(X)
print(df.groupby("Segment")[features].mean().round(1))
df.to_excel("customers_segmented.xlsx", index=False)
Why scale first?
K-means measures distance. Spend in rupees (thousands) would swamp orders (single digits). StandardScaler puts every column on the same scale so each counts equally.
Naming the segments
The algorithm only gives numbers 0β3. Look at the averages and name them yourself β for example loyal big spenders, new customers, at risk (high days since last order), occasional.
How many clusters?
for k in range(2, 9):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
print(k, round(km.inertia_))
Inertia always falls as k grows; look for the “elbow” where it stops falling quickly. Then pick the number your team can actually act on β four segments you use beat nine you ignore.
π Practice files for this article
- πAll code from this post2 examples in one file, ready to open in your editor.β¬ PY Β· 924 B
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Atul (AJ) builds office-automation and local-first AI tools as Atulya AI, and works with Excel, SAP and Oracle EPM every day. He writes about the shortcuts, macros and automations that actually save time β plus the occasional wacky fact. Videos on YouTube: Lazy Automator AI (@LazyAutomatorAI).
More posts by Atul βStuck on a step? Ask a question and the AI answers using this article.