v0.1.2
One consistent, beginner-friendly API for K-Means and Agglomerative (Hierarchical) Clustering on pandas DataFrames.
Install · Quick start · Run it in · Documentation · API reference
Why clustereasy
Clustering in scikit-learn works great, but K-Means and Agglomerative Clustering use different code, different parameters, and different plotting/evaluation steps — which gets confusing if you just want to explore a dataset.
clustereasy wraps both behind one object with one consistent set of
methods:
cluster = Cluster(data=df)
cluster.fit_kmeans(n_clusters=3) # or cluster.fit_agglomerative(n_clusters=3)
cluster.plot_clusters(x="col_a", y="col_b")
cluster.evaluate()
cluster.get_clustered_data()
- 🧭 One API, two algorithms — switch between K-Means and Agglomerative without relearning anything
- 🧼 Never mutates your data — your original DataFrame stays untouched
- 🛑 Explicit, beginner-friendly errors — no silent wrong behavior on bad input
- 🔧 Escape hatches for advanced users — every underlying scikit-learn parameter is exposed
- 📊 Built-in plots & metrics — elbow curves, dendrograms, silhouette plots, PCA projections
📦 Installation
pip install clustereasy
Local development install (editable, with test tools)
git clone https://github.com/shashikant-ds636/easycluster.git
cd easycluster
pip install -e ".[dev]"
Requirements: Python ≥ 3.9 · pandas ≥ 1.5 · NumPy ≥ 1.23 · scikit-learn ≥ 1.2 · SciPy ≥ 1.9 · Matplotlib ≥ 3.6
🚀 Quick start
import pandas as pd
from clustereasy import Cluster
df = pd.read_csv("customers.csv")
cluster = Cluster(
data=df,
features=["Annual Income", "Spending Score"],
scale=True,
missing="median",
)
cluster.elbow_method(max_clusters=10)
cluster.fit_kmeans(n_clusters=4, random_state=42)
cluster.plot_clusters(x="Annual Income", y="Spending Score")
print(cluster.evaluate())
result_df = cluster.get_clustered_data(column_name="Segment")
🧪 Run it in
Runnable end-to-end scripts also live in examples/:
kmeans_example.py ·
agglomerative_example.py ·
clustereasy_quickstart.ipynb
📖 Documentation
DataFrame input requirements
Cluster(data=df, features=[...], scale=..., missing=...)
data— a non-emptypandas.DataFrame. Never modified in place.features— optional list of column names to cluster on. Defaults to all columns. Columns must exist, be unique, and be numeric — clustereasy will not silently convert text/categorical values into numbers. Encode categorical columns yourself first (e.g.pd.get_dummies) if you want to include them.missing— one of"raise"(default),"drop","mean","median". Controls how missing values in the selected features are handled.- Infinite values always raise an explicit error — never silently dropped.
scale—False(default),True(same as"standard"), or one of"standard"/"minmax"/"robust".
K-Means tutorial
cluster = Cluster(data=df, features=["Income", "Score"], scale=True)
# Explore how many clusters might make sense
elbow_table = cluster.elbow_method(max_clusters=10, random_state=42)
# Fit
cluster.fit_kmeans(n_clusters=4, init="k-means++", n_init=10, random_state=42)
cluster.cluster_centers() # DataFrame, original feature scale by default
cluster.inertia() # WCSS for the fitted model
cluster.predict(new_df) # assign new rows to existing clusters
Supported fit_kmeans parameters: n_clusters, init, n_init, max_iter,
tol, random_state, algorithm — all pass straight through to
scikit-learn's KMeans.
Elbow Method. elbow_method(max_clusters=10, random_state=42, show=True)
fits K-Means for k = 1..max_clusters, plots k vs. WCSS, and returns a
DataFrame of results so you can reuse them without refitting. The elbow is a
heuristic, not a guaranteed optimum — pair it with silhouette_score()
and domain knowledge.
Hierarchical Clustering tutorial
Z = cluster.plot_dendrogram(method="ward", metric="euclidean")
cluster.fit_agglomerative(n_clusters=3, linkage="ward")
Supported linkage methods: ward, complete, average, single. ward
linkage requires metric="euclidean" — any other metric raises a clear error
instead of silently producing wrong results.
Cluster by distance instead of a fixed count:
cluster.fit_agglomerative(n_clusters=None, distance_threshold=5.0)
distance_threshold and n_clusters are mutually exclusive, matching
scikit-learn's own requirement.
Note:
AgglomerativeClusteringhas no nativepredict()in scikit-learn.Cluster.predict()will raise a clear error if called on an agglomerative model rather than faking support for it.
Dendrogram interpretation
- Each leaf is one observation.
- Each join (inverted "U") merges two clusters; its height is the distance at which they were merged.
- Cutting the dendrogram horizontally at a given height determines how many clusters you get at that distance.
- For large datasets, pass
truncate_mode="lastp"with a smallp— clustereasy warns above ~2000 samples if you don't.
Evaluation metrics and their limitations
All metrics work without ground-truth labels:
| Method | Notes |
|---|---|
silhouette_score() |
Needs 2..n-1 distinct clusters |
silhouette_samples() |
Per-sample values, same constraints |
davies_bouldin_score() |
Lower is better · needs ≥ 2 clusters |
calinski_harabasz_score() |
Higher is better · needs ≥ 2 clusters |
inertia() |
K-Means only — not available for Agglomerative models |
evaluate() |
One DataFrame with every metric applicable to the fitted model |
These are diagnostic tools, not proof of a "correct" clustering — sanity
check against domain knowledge. If a metric can't be computed (e.g. 1
distinct cluster), evaluate() shows NaN with a note instead of crashing;
individual metric methods raise ParameterError.
Feature scaling & missing-value handling
- Distances (and therefore both algorithms' results) are scale-sensitive. If
features are on different scales (e.g. income in thousands vs. a 1–100
score), set
scale=True. - K-Means centers are available both in the transformed (scaled) space
(
cluster._model.cluster_centers_) and inverse-transformed back to original feature scale (cluster.cluster_centers(), the default). - Missing values are never silently dropped — choose
missing="drop"/"mean"/"median"explicitly, or clean the data yourself.
Visualization
cluster.plot_clusters(x="Income", y="Score", show_centers=True)
cluster.plot_cluster_sizes()
cluster.plot_silhouette()
cluster.plot_pca() # for >2 features — clearly labeled as a 2D projection
plot_clusters requires exactly two selected feature columns. For
higher-dimensional data use plot_pca() instead.
Cluster labels & DataFrame output
labels = cluster.get_labels() # pd.Series, original index
clustered_df = cluster.get_clustered_data("Segment") # original df + label column
summary = cluster.cluster_summary() # size, proportion, per-feature mean
Cluster IDs (0, 1, 2, ...) are arbitrary identifiers — no inherent ranking or meaning.
Common errors and solutions
| Error | Likely cause | Fix |
|---|---|---|
InputValidationError: not numeric |
Selected a text/categorical column | Encode it first, or exclude from features |
InputValidationError: missing values |
NaNs present, default missing="raise" |
Pass missing="drop"/"mean"/"median" |
ParameterError: Ward linkage requires metric='euclidean' |
linkage="ward" with another metric |
Use metric="euclidean" or a different linkage |
NotFittedError |
Called an evaluation/plot/output method before fitting | Call fit_kmeans/fit_agglomerative first |
ParameterError on predict() |
Called predict() on an Agglomerative model |
Not supported — K-Means only |
Computational limitations
- Dendrograms require O(n²) memory/time and are impractical past a few thousand samples.
AgglomerativeClusteringscales worse thanKMeansfor large n.- No GPU acceleration — this wraps scikit-learn/SciPy CPU implementations.
🔖 API reference
| Category | Methods |
|---|---|
| Construction | Cluster(data, features=None, scale=False, missing="raise") |
| K-Means | elbow_method, fit_kmeans, cluster_centers, inertia, predict |
| Agglomerative | plot_dendrogram, get_linkage_matrix, fit_agglomerative |
| Shared plots | plot_clusters, plot_cluster_sizes, plot_silhouette, plot_pca |
| Evaluation | silhouette_score, silhouette_samples, davies_bouldin_score, calinski_harabasz_score, evaluate |
| Output | get_labels, get_clustered_data, cluster_summary, elbow_results |
✅ Testing
pip install -e ".[dev]"
pytest -q
Current suite: 59 tests, all passing — covering validation, both algorithms, visualization, evaluation edge cases, and DataFrame-output guarantees (index preservation, immutability, reproducibility).
🗺️ Roadmap
DBSCAN,OPTICS,GaussianMixturesupport behind the same API- Automatic comparison across multiple
k/ linkage configurations - Model save/load (
joblib) - Direct CSV export of results
- Connectivity-constrained agglomerative clustering helpers
🤝 Contributing
- Fork, branch from
main. - Add/update tests for any behavior change.
- Run
pytest -qbefore opening a PR. - Keep public methods documented with docstrings.
📤 Preparing a release
pip install build twine
python -m build
twine check dist/*
pip install dist/clustereasy-0.1.2-py3-none-any.whl # test locally
twine upload --repository testpypi dist/* # TestPyPI first
twine upload dist/* # then PyPI
Bump version in pyproject.toml (and __version__ in
src/clustereasy/__init__.py) before each release and update
CHANGELOG.md.
Metadata
Release files for clustereasy 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| clustereasy-0.1.2.tar.gz | 24.1 kB | With provenance | Details for clustereasy-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| clustereasy-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for clustereasy-0.1.2-py3-none-any.whl |
Total release size: 43.0 kB
Release files / clustereasy-0.1.2.tar.gz
| Download URL | clustereasy-0.1.2.tar.gz |
|---|---|
| Size | 24.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
207e4e6e35d020370ce3274e724b4f754f319743229cae9020fc60e3e67354be
|
|
BLAKE2b-256 checksum How to use checksums |
eb230dccb4cee3bcd6d18b0a7853bf50fe66f458405e0675873c8b1959c13aee
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logRelease files / clustereasy-0.1.2-py3-none-any.whl
| Download URL | clustereasy-0.1.2-py3-none-any.whl |
|---|---|
| Size | 18.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
04cc853301e6b337ca06e22c9b1776f6cac010bcb0dc203f3604cbb07f71b194
|
|
BLAKE2b-256 checksum How to use checksums |
b0682e6cd7904fb7f1259c5aaba4405962bd3abfbe9cb3763c77c2561ceafb13
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logSecurity for clustereasy 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for clustereasy-0.1.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.