Goal
Given Spotify song features, answer:
- What does popularity distribution look like?
- Which audio features correlate with popularity?
- Do genres differ in average popularity?
Analysis pipeline
flowchart LR A["Raw features
(danceability, energy, ...)"] --> B["Explore
(describe, distribution)"] B --> C["Correlate
(features vs popularity)"] C --> D["Visualize
(heatmap)"] D --> E["Conclude
(what predicts popularity)"]
Step 1: Load
import pandas as pd
df = pd.read_csv("data/spotify.csv")
print(df.head())Step 2: Popularity distribution
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 4))
sns.histplot(df["popularity"], bins=30, kde=True)
plt.title("Popularity distribution")
plt.tight_layout()
plt.show()Step 3: Correlations
import seaborn as sns
import matplotlib.pyplot as plt
num = df.select_dtypes(include="number")
plt.figure(figsize=(8, 6))
sns.heatmap(num.corr(), cmap="coolwarm", center=0)
plt.title("Correlation heatmap")
plt.tight_layout()
plt.show()Visualize it
Deliverable
- Top correlated features
- Whether correlations are meaningful or driven by outliers
Check your understanding
Why check a scatter plot as well as the corr() number?
The project asks whether correlations are meaningful or driven by outliers.
Show answer
A — A strong correlation can be driven by a couple of outlier songs — The project asks whether correlations are meaningful or driven by outliers.
What does num = df.select_dtypes(include="number") do before the heatmap?
Correlation needs numeric columns, so text columns such as genre are excluded.
Show answer
A — Keeps only numeric columns so corr() works — Correlation needs numeric columns, so text columns such as genre are excluded.
Why does the heatmap use center=0 with cmap="coolwarm"?
A diverging colormap centered at zero makes the sign of each correlation visible.
Show answer
A — Zero correlation gets the neutral color and positive and negative are shown in opposite colors — A diverging colormap centered at zero makes the sign of each correlation visible.
What does sns.histplot(df["popularity"], bins=30, kde=True) show?
It answers the first question, what the popularity distribution looks like.
Show answer
A — The shape of the popularity distribution with a smooth density curve — It answers the first question, what the popularity distribution looks like.
🧪 Try It Yourself
Exercise 1 – Summary statistics
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 – Correlation matrix
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 – Select only numeric columns
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.