K-Means Clustering

Python · Advanced Python & AI

Theory

K-Means is an unsupervised algorithm that groups unlabelled data into K clusters. It starts by placing K centroids, assigns every point to its nearest centroid, moves each centroid to the mean of the points assigned to it, and repeats the assign-and-update steps until the assignments stop changing. The result is a cluster label for every point and a centre for every cluster (cluster_centers_).

In the diagram, six points form two obvious groups; with n_clusters=2 the first three get label 0 (centre about (1.33, 3)) and the last three label 1 (centre about (8.33, 8)). The label numbers themselves are arbitrary. You must choose K: the elbow method plots inertia_ (total squared distance to centres) for several K values and looks for the bend. Scale features first, set random_state for repeatable results, and remember K-Means assumes roughly round, similar-sized clusters.

Why we use it

Often there is no label to predict, only data to understand. K-Means finds natural groups - customer segments, product types, behaviour patterns - so you can describe and act on each group.

When to use it

Use it for segmentation on numeric, scaled features when you expect compact, roughly spherical clusters. For odd shapes or noise points try DBSCAN; when you do have labels, use a classifier instead.

How it works

  1. Choose K and place K initial centroids
  2. Assign every point to its nearest centroid
  3. Move each centroid to the mean of its points
  4. Did any assignment change? Yes: Repeat assign and update. No: Stop: clusters are stable.
  5. Cluster labels and centroids

Syntax

from sklearn.cluster import KMeans
model = KMeans(n_clusters=3).fit(X)

Example

model = KMeans(n_clusters=3, random_state=42)
labels = model.fit_predict(X)

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