To run K-means clustering in Python, scale your columns with StandardScaler, then call KMeans(n_clusters=3, random_state=0).fit_predict(X_scaled) from scikit-learn. It returns a cluster number for every row, and cluster_centers_ holds the center of each cluster.
Quick Example
This example makes up 600 coffee shop customers with two measurements each, groups them into three clusters, and plots the result with the centers marked.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(19)
groups = [ # customers, visits per month, average order ($), share ordered in app
(260, (4, 1.5), (6.5, 1.5), (0.15, 0.08)),
(200, (18, 3.0), (5.5, 1.2), (0.75, 0.10)),
(140, (6, 2.0), (17.0, 3.0), (0.40, 0.12)),
]
customers = pd.concat([pd.DataFrame({
"visits": rng.normal(*visits, size),
"order_value": rng.normal(*order, size),
"app_share": rng.normal(*app, size),
}) for size, visits, order, app in groups], ignore_index=True)
customers = customers.clip(lower=0).assign(app_share=lambda d: d.app_share.clip(upper=1))
features = ["visits", "order_value"]
model = make_pipeline(StandardScaler(), KMeans(n_clusters=3, random_state=19))
customers["cluster"] = model.fit_predict(customers[features])
# Centers come back in scaled units, so convert them to visits and dollars
scaler, kmeans = model[0], model[1]
centers = scaler.inverse_transform(kmeans.cluster_centers_)
colors = ["#0f766e", "#d97706", "#7c3aed"]
fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
for cluster, color in enumerate(colors):
rows = customers[customers.cluster == cluster]
ax.scatter(rows.visits, rows.order_value, s=18, color=color, alpha=0.6,
label=f"Cluster {cluster} ({len(rows)} customers)")
ax.scatter(centers[:, 0], centers[:, 1], marker="X", s=220, color="black",
edgecolor="white", linewidth=1.5, label="Centers")
ax.set(title="Coffee shop customers in three clusters",
xlabel="Visits per month", ylabel="Average order ($)")
ax.legend()
plt.show()

The three clusters are 267 occasional, low-spend customers (about 4 visits and $6.50 an order), 197 frequent visitors (about 18 visits and $5.50), and 136 customers with large orders (about $17). fit_predict() fits the model and labels the rows in one call.
Why Should I Scale Data Before K-Means?
K-means assigns each row to the nearest center by straight-line distance, so a column with large numbers dominates. To see it, express spend as yearly cents instead of dollars per order and cluster with and without scaling.
from sklearn.metrics import adjusted_rand_score
X = pd.DataFrame({"visits": customers.visits,
"yearly_cents": customers.visits * customers.order_value * 1200})
raw = KMeans(n_clusters=3, random_state=19).fit_predict(X)
scaled = make_pipeline(StandardScaler(),
KMeans(n_clusters=3, random_state=19)).fit_predict(X)
fig, axes = plt.subplots(1, 2, figsize=(10, 4.3), sharey=True, layout="constrained")
for ax, labels, title in [(axes[0], raw, "Not scaled"),
(axes[1], scaled, "Scaled with StandardScaler")]:
ax.scatter(X.visits, X.yearly_cents / 100, c=labels, s=14,
cmap="Dark2", vmin=0, vmax=7)
ax.set(title=title, xlabel="Visits per month")
axes[0].set_ylabel("Yearly spend ($)")
plt.show()

Without scaling, the clusters are horizontal bands of yearly spend, and the number of visits has almost no say. After scaling, the frequent visitors form their own cluster. Both runs use the same data and settings, and their labels agree poorly (adjusted Rand index of 0.58, where 1 means identical groupings).
StandardScaler gives each column a mean of 0 and a standard deviation of 1. That is a choice too: it says a one standard deviation difference counts equally in every column. If a column has a long tail, such as spend, taking its logarithm before scaling often helps.
Describe Each Cluster with a Profile Heatmap
With more than two columns, compare the average of each column by cluster. Color the cells by how far each average sits from the overall mean, and print the real values inside them.
import seaborn as sns
columns = ["visits", "order_value", "app_share"]
segmenter = make_pipeline(StandardScaler(), KMeans(n_clusters=3, random_state=19))
customers["segment"] = segmenter.fit_predict(customers[columns])
profile = customers.groupby("segment")[columns].mean()
relative = (profile - customers[columns].mean()) / customers[columns].std()
sizes = customers.segment.value_counts().sort_index()
print(profile.round(2))
fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
sns.heatmap(relative, annot=profile, fmt=".2f", cmap="PuOr_r", center=0, ax=ax,
cbar_kws={"label": "Standard deviations\nfrom the average"},
xticklabels=["Visits per month", "Average order ($)", "App share"],
yticklabels=[f"Segment {i} (n={n})" for i, n in sizes.items()])
ax.set(title="Segment profiles", ylabel="")
ax.tick_params(axis="y", rotation=0)
plt.show()

Segment 0 visits about 4 times a month and rarely uses the app. Segment 1 visits about 18 times and places 76% of orders in the app. Segment 2 spends about $16.75 an order. These are names you can act on, which "cluster 1" isn't. Adding app_share moved a few customers, so the segment sizes differ slightly from the first chart.
Assign New Customers to a Cluster
Call predict() on the fitted pipeline. It applies the same scaling, then picks the nearest center. transform() returns the distance to every center, which shows how close a call it was.
new = pd.DataFrame({"visits": [15, 5], "order_value": [6.0, 14.0],
"app_share": [0.8, 0.3]})
print("segment:", segmenter.predict(new))
print("distances:", segmenter.transform(new).round(2), sep="\n")
The first new customer lands in segment 1, the frequent app users, and the second in segment 2. Each distance row has one value per segment, and the smallest wins.
Save the fitted pipeline, not only the labels. Refitting on new data can move the centers and renumber the clusters.
How the K-Means Algorithm Works
K-means picks starting centers, assigns every point to the nearest one, moves each center to the mean of its points, and repeats until the assignments stop changing. This plot runs it from three deliberately poor starting points.
Z = StandardScaler().fit_transform(customers[features])
start = Z[[0, 1, 2]] # three rows from the same group
fig, axes = plt.subplots(1, 4, figsize=(12, 3.5), sharex=True, sharey=True,
layout="constrained")
axes[0].scatter(Z[:, 0], Z[:, 1], color="#cbd5e1", s=8)
axes[0].scatter(*start.T, marker="X", s=150, color="black", edgecolor="white")
axes[0].set_title("Starting centers")
for ax, steps in zip(axes[1:], [1, 2, 100]):
step = KMeans(n_clusters=3, init=start, n_init=1, max_iter=steps).fit(Z)
ax.scatter(Z[:, 0], Z[:, 1], c=step.labels_, s=8, cmap="Dark2", vmin=0, vmax=7)
ax.scatter(*step.cluster_centers_.T, marker="X", s=150, color="black",
edgecolor="white")
ax.set_title(f"After {step.n_iter_} iteration{'s' if step.n_iter_ > 1 else ''}")
fig.supxlabel("Visits per month (scaled)")
fig.supylabel("Order value (scaled)")
plt.show()

All three centers start inside one group. After one iteration they are already pulling apart, and after four the assignments stop changing.
The default init="k-means++" spreads the starting centers apart, which usually avoids slow or poor runs. Since scikit-learn 1.4, n_init="auto" is the default and runs it once with that method. On messier data, set n_init=10 to try ten starts and keep the best.
When K-Means Gives Poor Clusters
K-means works best on compact, round groups of similar spread. Compare it with other scikit-learn methods on two other shapes.
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_blobs, make_moons
from sklearn.mixture import GaussianMixture
moons, _ = make_moons(500, noise=0.06, random_state=19)
blobs, _ = make_blobs(600, centers=[(-2, 0), (2, 0), (7, 0)],
cluster_std=0.7, random_state=19)
stretched = blobs @ np.array([[0.35, 0], [0.9, 1.0]])
results = [
("Moons: K-means", moons, KMeans(2, random_state=19).fit_predict(moons)),
("Moons: DBSCAN", moons, DBSCAN(eps=0.2).fit_predict(moons)),
("Stretched: K-means", stretched,
KMeans(3, random_state=19).fit_predict(stretched)),
("Stretched: Gaussian mixture", stretched,
GaussianMixture(3, n_init=5, random_state=19).fit_predict(stretched)),
]
fig, axes = plt.subplots(2, 2, figsize=(9, 7), layout="constrained")
for ax, (title, data, labels) in zip(axes.flat, results):
ax.scatter(data[:, 0], data[:, 1], c=labels, s=10, cmap="Dark2", vmin=0, vmax=7)
ax.set(title=title, xticks=[], yticks=[])
plt.show()

K-means splits both moons, because a boundary between two centers is a straight line. It also cuts across the stretched groups. DBSCAN follows the moons by connecting nearby points, and the Gaussian mixture models each stretched group's shape. Decision boundary plots show the same kind of straight-versus-curved difference for classifiers.
| Method | Use it when | Set in advance |
|---|---|---|
KMeans |
Groups are compact and similar in size and spread | Number of clusters |
MiniBatchKMeans |
The data is too large for full K-means | Number of clusters |
GaussianMixture |
Groups are elongated or differ in spread, or you want membership probabilities | Number of components |
DBSCAN / HDBSCAN |
Groups have irregular shapes, or some rows are noise | Density settings |
Practical Tips
- Choose the number of clusters with an elbow plot and silhouette scores, then check that each cluster means something you can act on.
- Cluster numbers are arbitrary. Name segments from their profiles, not their numbers.
- K-means always returns the number of clusters you ask for, including on data with no groups.
- Outliers pull centers toward them. Look at a scatter plot or histogram before fitting.
- To plot clusters found in many columns, project the data with PCA or t-SNE or UMAP.