Understand the idea
Cluster labels may be permuted without changing the grouping. Report original-unit feature summaries and population sizes so the result is interpretable.
sizes and original-unit profiles with named features.Scroll the diagram horizontally if needed.What the syntax does
X.groupby(labels)- Groups original-unit rows by their aligned fitted assignments.
pd.Series(labels).value_counts()- Counts how many fitted observations belong to each named group.
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']] scaled- Standardised features in the same row/column order as
X.scaled = StandardScaler().fit_transform(X) labels- One cluster label per fitted row; equivalent consistent label names are accepted.
labels = KMeans(n_clusters=3, n_init=20, random_state=42).fit_predict(scaled)
Outputs you create
answer- The requested result, with the values, labels and row order described by this task.
sizes- Group
sizesindexed by cluster label.
- Group
island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex | year |
|---|---|---|---|---|---|---|
| Torgersen | 39.1 | 18.7 | 181 | 3750 | male | 2007 |
| Torgersen | 39.5 | 17.4 | 186 | 3800 | female | 2007 |
| Torgersen | 40.3 | 18 | 195 | 3250 | female | 2007 |
| Torgersen | 36.7 | 19.3 | 193 | 3450 | female | 2007 |
| Torgersen | 39.3 | 20.6 | 190 | 3650 | male | 2007 |
| Torgersen | 38.9 | 17.8 | 181 | 3625 | female | 2007 |
| Torgersen | 39.2 | 19.6 | 195 | 4675 | male | 2007 |
| Torgersen | 41.1 | 17.6 | 182 | 3200 | female | 2007 |
- Report cluster
sizesand original-unit means.
answersizesHints
Think: Assignments must align with the original rows whose profiles you report.
Tools: groupby.mean and value_counts.
Approach: Use the supplied labels to aggregate original measurements and count group membership.
Explained solution
answer=X.groupby(labels).mean()
sizes=pd.Series(labels).value_counts().sort_index()
Original-unit means explain group characteristics while sizes reveal whether a profile describes many rows or a tiny subset.