Skip to content

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()
# INFO
penguins_df.info()
# OVERALL STATISTICS
print(penguins_df.describe())
import matplotlib.pyplot as plt

# Scatter plot of culmen length vs. culmen depth
plt.figure(figsize=(8, 6))
plt.scatter(penguins_df['culmen_length_mm'], penguins_df['culmen_depth_mm'], alpha=0.7)

plt.title('Scatter Plot of Culmen Length vs Culmen Depth')
plt.xlabel('Culmen Length (mm)')
plt.ylabel('Culmen Depth (mm)')
plt.grid(True)
plt.show()
# Remove non-numeric columns for clustering
df = penguins_df.select_dtypes(include=['float64', 'int64'])
df.head()
# Standardize the data
scaler = StandardScaler()
scaled_data = scaler.fit_transform(df)
scaled_df = pd.DataFrame(scaled_data)
scaled_df.head()
# Apply KMeans clustering with 3 clusters
kmeans = KMeans(n_clusters=3, random_state=0)
penguins_df['cluster'] = kmeans.fit_predict(scaled_data)

# Calculate the mean of each column by cluster
stat_penguins = penguins_df.groupby('cluster').mean()
stat_penguins.head()
import matplotlib.pyplot as plt

# Scatter plot comparing culmen length and flipper length by cluster
plt.figure(figsize=(8, 6))
plt.scatter(stat_penguins['culmen_length_mm'], stat_penguins['flipper_length_mm'], c='blue', s=100)

# Label each point with the cluster index
for i in range(len(stat_penguins)):
    plt.text(stat_penguins['culmen_length_mm'][i] + 0.1, 
             stat_penguins['flipper_length_mm'][i] + 0.1, 
             f'Cluster {i}', fontsize=9)

plt.title('Cluster Comparison of Culmen Length and Flipper Length')
plt.xlabel('Culmen Length (mm)')
plt.ylabel('Flipper Length (mm)')
plt.grid(True)
plt.show()