# Code examples from: Group Customers Automatically with K-Means in Python (From an Excel File)
# https://www.atulvij.com/k-means-customer-segments-python
# Review and adapt before running; examples use sample values.

# ---- Example 1 (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)

# ---- Example 2 (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_))

