Skip to content
Project: Clustering Antarctic Penguin Species

Alt text source: @allison_horst https://github.com/allisonhorst/penguins

You have been asked to support a team of researchers who have been collecting data about penguins in Antartica! The data is available in csv-Format as penguins.csv

Origin of this data : Data were collected and made available by Dr. Kristen Gorman and the Palmer Station, Antarctica LTER, a member of the Long Term Ecological Research Network.

The dataset consists of 5 columns.

ColumnDescription
culmen_length_mmculmen length (mm)
culmen_depth_mmculmen depth (mm)
flipper_length_mmflipper length (mm)
body_mass_gbody mass (g)
sexpenguin sex

Unfortunately, they have not been able to record the species of penguin, but they know that there are at least three species that are native to the region: Adelie, Chinstrap, and Gentoo. Your task is to apply your data science skills to help them identify groups in the dataset!

# Import Required Packages
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# Loading and examining the dataset
penguins_df = pd.read_csv("penguins.csv")
penguins_df.head()
# Convert 'MALE' to 0 and 'FEMALE' to 1 in the 'sex' column
penguins_df['sex'] = penguins_df['sex'].map({'MALE': 0, 'FEMALE': 1})

# Display the first few rows to verify the changes
penguins_df.head()
model = KMeans(n_clusters=6)

model.fit(penguins_df)
# Add the cluster labels to the dataframe
penguins_df['cluster'] = model.labels_

# Plotting the clusters
plt.figure(figsize=(10, 6))

# Scatter plot for each cluster
for cluster in range(6):
    clustered_data = penguins_df[penguins_df['cluster'] == cluster]
    plt.scatter(clustered_data['flipper_length_mm'], clustered_data['body_mass_g'], label=f'Cluster {cluster}')

# Adding labels and title
plt.xlabel('flipper length')
plt.ylabel('body mass')
plt.title('Penguin Clusters')
plt.legend()
plt.show()
# Add the cluster labels to the dataframe
# penguins_df['cluster'] = model.labels_

# Calculate the average values for each cluster
stat_penguins = penguins_df.groupby('cluster').mean()

# Display the resulting dataframe
stat_penguins = stat_penguins.drop(columns=['sex'])
stat_penguins