K-Means Clustering

Python · Machine Learning (Scikit-Learn)

Theory

K-Means is an unsupervised algorithm that splits rows into k groups of similar points. It starts with k random centres, assigns every point to its nearest centre, moves each centre to the mean of its assigned points and repeats until the assignments stop changing. labels_ gives each row's cluster and cluster_centers_ the centres. n_init=10 runs the whole process from 10 different starts and keeps the best, because one bad start can give poor clusters.

You must choose k. The elbow method fits k = 1, 2, 3 ... and plots inertia_, the total squared distance from points to their centres. Inertia always falls as k grows, but the drop flattens after the natural number of groups, which forms an elbow in the curve. Scale features first, since K-Means uses distances, and remember it finds round, similar-sized clusters best.

Why we use it

Many datasets have no labels but hide natural groups, such as customer segments by visits and spend. K-Means finds them quickly, so marketing, pricing or product teams can treat each segment differently.

When to use it

Use K-Means for segmentation on scaled numeric features when you expect compact, roughly round groups. Try the elbow method and inspect the centres to name the segments. For odd-shaped clusters or noise, DBSCAN or hierarchical clustering fit better.

How it works

  1. Scaled numeric features
  2. Pick k and place k starting centres
  3. Assign every point to its nearest centre
  4. Move each centre to the mean of its points
  5. Did any assignment change? Yes: Repeat assign and move. No: Converged.
  6. labels_, cluster_centers_, inertia_

Syntax

from sklearn.cluster import KMeans
km = KMeans(n_clusters=3, n_init=10, random_state=0)
km.fit(X_scaled)
km.labels_  km.cluster_centers_  km.inertia_
km.predict(X_new_scaled)

Example

km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X_scaled)
print(km.labels_[:10])
print(km.inertia_)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic