
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.
In this article
“`python
# 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?
“`python
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.