📄 Documented Code: Music Data Preprocessing &
Mood Classification
This script performs data cleaning, normalization, and mood classification for a song
dataset.
🛠 Step-by-Step Explanation
1️⃣ Core Concept – What is This Code Doing?
This code cleans and prepares a dataset for analysis by:
✔ Handling duplicates & missing values to ensure data integrity.
✔ Normalizing numerical features (danceability, energy, valence) for consistency.
✔ Classifying songs into moods (Happy, Sad, Angry, Calm, Neutral) based on energy &
valence.
2️⃣ Key Insights – Important Aspects of This Code
🔹 Data Cleaning
python
CopyEdit
df = df.drop_duplicates() # Remove duplicate rows
df = [Link]() # Remove missing values
● Removes duplicates to ensure unique song entries.
● Drops missing values, as missing data can affect analysis.
🔹 Feature Normalization
python
CopyEdit
num_cols = ['danceability', 'energy', 'Valence']
scaler = MinMaxScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
● Why normalize?
○ Some features may have different value ranges (e.g., energy from 0-1, tempo
in BPM).
○ MinMaxScaler transforms values to a 0-1 range for consistency.
🔹 Mood Classification Based on Energy & Valence
python
CopyEdit
def add_mood_column(df):
conditions = [
(df['Valence'] > 0.6) & (df['energy'] > 0.6), # Happy
(df['Valence'] < 0.4) & (df['energy'] < 0.4), # Sad
(df['Valence'] < 0.4) & (df['energy'] > 0.6), # Angry
(df['Valence'] > 0.6) & (df['energy'] < 0.4), # Calm
]
choices = ['Happy', 'Sad', 'Angry', 'Calm']
df['mood'] = [Link](conditions, choices, default='Neutral')
# Assign mood
return df
df = add_mood_column(df)
● How does this work?
○ Valence: Measures how positive the song sounds (0 = sad, 1 = happy).
○ Energy: Measures intensity (0 = low, 1 = high).
○ Mood Categories:
■ Happy → High energy, high valence
■ Sad → Low energy, low valence
■ Angry → High energy, low valence
■ Calm → Low energy, high valence
■ Neutral → Everything else
3️⃣ Practical Takeaway – How Is This Applied in Real Life?
✅ Music Streaming Services: Platforms like Spotify, Apple Music, YouTube Music use
✅ AI-Driven Playlists: Personalized playlists (e.g., "Happy Hits," "Sad Vibes") use similar
mood-based classification for playlists & recommendations.
✅ Sentiment Analysis in Music: Understanding a song’s mood helps in emotion-based
mood tagging.
applications (e.g., AI DJ, mental wellness apps).
📜 Full Documented Code
python
📌
CopyEdit
# Import necessary libraries
import pandas as pd
import numpy as np
from [Link] import MinMaxScaler
# =============================================================
# 1️⃣ Load Dataset
# =============================================================
file_path = "C:/music/preprocessed_songs.csv" # Path to dataset
df = pd.read_csv(file_path) # Load data into Pandas DataFrame
# 🔹 Display first few rows to inspect data
print("🔹 First 5 rows of dataset:")
print([Link]())
# =============================================================
# 2️⃣ Data Cleaning
# =============================================================
# 🔹 Remove duplicate rows
"""
Duplicates can distort data analysis. This step ensures that each
song appears only once.
"""
df = df.drop_duplicates()
# 🔹 Handle missing values
"""
Missing values can cause errors in data processing. Here, we drop
rows with missing data.
Alternatively, missing values could be filled using imputation.
"""
df = [Link]()
# 🔹 Display new dataset shape after cleaning
print("\n✅ Data cleaned. Shape of dataset:", [Link])
# =============================================================
# 3️⃣ Feature Normalization
# =============================================================
# 🔹 Select numerical columns for normalization
num_cols = ['danceability', 'energy', 'Valence']
# 🔹 Apply MinMax Scaling to standardize features
"""
MinMaxScaler transforms numerical values into a [0,1] range.
This prevents features with larger values from dominating others.
"""
scaler = MinMaxScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
print("\n ✅ Numerical features normalized.")
# =============================================================
# 4️⃣ Mood Classification Based on Valence & Energy
# =============================================================
def add_mood_column(df):
"""
Assigns a mood label based on valence and energy levels.
Parameters:
- df (DataFrame): The input dataset.
Returns:
- df (DataFrame): The dataset with an added "mood" column.
Mood Categories:
- Happy: High energy & high valence (>0.6)
- Sad: Low energy & low valence (<0.4)
- Angry: High energy & low valence
- Calm: Low energy & high valence
- Neutral: Default category if none of the above apply.
"""
# Define conditions for each mood
conditions = [
(df['Valence'] > 0.6) & (df['energy'] > 0.6), # Happy
(df['Valence'] < 0.4) & (df['energy'] < 0.4), # Sad
(df['Valence'] < 0.4) & (df['energy'] > 0.6), # Angry
(df['Valence'] > 0.6) & (df['energy'] < 0.4), # Calm
]
# Define corresponding mood labels
choices = ['Happy', 'Sad', 'Angry', 'Calm']
# Assign moods to songs
df['mood'] = [Link](conditions, choices, default='Neutral')
return df
# 🔹 Apply mood classification
df = add_mood_column(df)
# =============================================================
# 5️⃣ Save the Processed Dataset
# =============================================================
# 🔹 Save the updated dataset with moods
df.to_csv("C:/music/preprocessed_songs.csv", index=False)
# 🔹 Print confirmation message
print("\n✅ Mood column added successfully!")
# 🔹 Display a sample of songs with their moods
print(df[['song_name', 'mood']].head(10))
🎯 Summary
✅ Removes duplicates & missing values to clean the dataset.
✅ Normalizes numerical features (danceability, energy, valence) using MinMaxScaler.
✅ Classifies songs into moods based on valence & energy.
✅ Saves the preprocessed dataset for further analysis.
🎵🚀
This mood-based classification is widely used in music recommendation systems and
AI-powered playlist generation!