36. K-Means Clustering in Python
36.4 India Customer / City Fictional Example
Why. Wire a full tiny India example: fictional grocery customers across Maharashtra cities.
What. Fit KMeans(n_clusters=3), attach cluster ids, and summarise means per cluster.
How.
Copy-run customer groups
- Build numeric X.
- Fit KMeans with n_init set (avoids warning noise).
- Add
clustercolumn. - groupby mean to name the groups.
import pandas as pd
from sklearn.cluster import KMeans
df = pd.DataFrame({
"customer": ["Ruhi", "Raja", "Rani", "Asha", "Vijay", "Meera", "Om", "Neha"],
"city": ["Pune", "Kolhapur", "Nashik", "Pune", "Mumbai", "Nagpur", "Pune", "Nashik"],
"orders_per_month": [2, 1, 9, 3, 11, 2, 10, 8],
"avg_basket_inr": [240, 190, 910, 310, 1250, 220, 980, 870],
})
X = df[["orders_per_month", "avg_basket_inr"]]
km = KMeans(n_clusters=3, n_init=10, random_state=42)
df["cluster"] = km.fit_predict(X)
print(df[["customer", "city", "cluster"]])
print(df.groupby("cluster")[["orders_per_month", "avg_basket_inr"]].mean().round(1))
What you should see. Three buckets — e.g. light shoppers vs heavy baskets. City is shown for colour; it was not used as a feature here so distance stays numeric and simple.
Fictional data
Names and baskets are classroom fiction only.