This code loads a CSV file containing a music playlist...

August 25, 2025 at 02:07 PM

import pandas as pd import numpy as np # load df = pd.read_csv("playlist.csv") # normalize if needed for col in ["Danceability","Energy","Valence"]: # detect 0-100 scale if df[col].max() > 1: df[col] = df[col] / 100.0 # helper: convert Thayer mood ranges to numeric targets (0-1 for D/E/V, BPM for tempo) MOODS = { "Happy": {"dance": 0.75, "energy": 0.85, "valence": 0.95, "tempo": 110}, "Exuberant": {"dance": 0.95, "energy": 0.975,"valence": 0.975,"tempo": 130}, "Energetic": {"dance": 0.90, "energy": 0.95, "valence": 0.85, "tempo": 130}, "Frantic": {"dance": 0.65, "energy": 0.95, "valence": 0.35, "tempo": 150}, "Anxious/Sad": {"dance": 0.35, "energy": 0.65, "valence": 0.30, "tempo": 90}, "Depression": {"dance": 0.10, "energy": 0.30, "valence": 0.10, "tempo": 50}, "Calm": {"dance": 0.30, "energy": 0.30, "valence": 0.85, "tempo": 70}, "Contentment": {"dance": 0.50, "energy": 0.60, "valence": 0.85, "tempo": 90}, } def score_tracks(df, target, weights=None): if weights is None: weights = {"dance":1.0,"energy":1.0,"valence":1.0,"tempo":1.0} # normalize tempo range to 0-1 to match others (use 40-160 BPM typical range) tempo_min, tempo_max = 40,160 t_norm = (df["Tempo"] - tempo_min) / (tempo_max - tempo_min) target_t_norm = (target["tempo"] - tempo_min) / (tempo_max - tempo_min) # compute Euclidean-ish distance (weighted) d_dance = (df["Danceability"] - target["dance"])**2 * weights["dance"] d_energy = (df["Energy"] - target["energy"])**2 * weights["energy"] d_val = (df["Valence"] - target["valence"])**2 * weights["valence"] d_tempo = (t_norm - target_t_norm)**2 * weights["tempo"] df = df.copy() df["score"] = np.sqrt(d_dance + d_energy + d_val + d_tempo) return df.sort_values("score") # example: top 20 happy tracks target = MOODS["Happy"] top20 = score_tracks(df, target).head(20) print(top20[["Track Name","Artist Name(s)","Danceability","Energy","Valence","Tempo","score"]])

This code loads a CSV file containing a music playlist and calculates a "mood-based similarity score" for each track, based on its attributes (e.g., danceability, energy, valence, tempo). Here's a breakdown of what it does:

Steps in the Code:

  1. Imports Necessary Libraries:

    • pandas is imported for data manipulation.
    • numpy is imported for mathematical computations.
  2. Loads the Data:

    • The playlist.csv file is loaded into a pandas DataFrame named df.
  3. Normalizes Columns:

    • The Danceability, Energy, and Valence columns are checked if their values exceed 1 (indicating a 0–100 scale rather than the standard 0–1 range for these attributes). If any column values are greater than 1, they are divided by 100, normalizing them to the 0–1 range.
  4. Defines Mood Targets:

    • A dictionary MOODS is defined. This maps "moods" like "Happy" or "Exuberant" to corresponding numeric targets for key features:
      • dance (danceability)
      • energy (energy level)
      • valence (positivity level)
      • tempo (beats per minute)
  5. Defines the score_tracks Function:

    • This function calculates a similarity "score" for each track in the dataset relative to a target mood. Here's how:
      • Normalizes Tempo: Tempo (BPM) is normalized to the range 0–1. The typical range of tempos is assumed to be 40 BPM (minimum) to 160 BPM (maximum).
      • Distance Calculation: It calculates the squared difference between the song's feature values (danceability, energy, valence, and normalized tempo) and the target mood values. A weight can optionally be applied to emphasize/de-emphasize specific attributes in the scoring.
      • Score Assignment: A new column, score, is added to the DataFrame, which contains the Euclidean distance-like value (square root of the sum of weighted squared differences) for each track. Lower scores indicate tracks that are closer to the target mood.
  6. Finds Top 20 Tracks for the "Happy" Mood:

    • The MOODS["Happy"] dictionary is used as the target mood.
    • The score_tracks function is called to calculate scores for all tracks relative to the "Happy" mood.
    • The tracks are sorted by their scores (from closest to most distant), and the top 20 tracks with the lowest scores are selected.
  7. Displays the Results:

    • The top 20 tracks are printed, displaying their:
      • Track Name
      • Artist Name(s)
      • Danceability
      • Energy
      • Valence
      • Tempo
      • Score

Overall Purpose:

  • The code recommends tracks in a playlist that match a desired "mood" by comparing their key musical attributes (danceability, energy, valence, tempo) to predefined target values for different moods. In this example, the top 20 songs closest to the "Happy" mood are displayed.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node