Group Customers Automatically with K-Means in Python (From an Excel File)

Group Customers Automatically with K-Means in Python (From an Excel File) featured illustration

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 2 min readUpdated 28 September 2026

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
  1. Why scale first?
  2. Naming the segments
  3. How many clusters?
  4. Continue 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.

Advertisement

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.

πŸ’‘ Re-run monthly and compare how customers move between segments. “Loyal β†’ at risk” is a list worth a phone call.

πŸ“Ž 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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong