Skip to content

Instantly share code, notes, and snippets.

@makispl
Last active March 8, 2020 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makispl/d8e3be4b51a8e4e9b9d8e11e668daa21 to your computer and use it in GitHub Desktop.
Save makispl/d8e3be4b51a8e4e9b9d8e11e668daa21 to your computer and use it in GitHub Desktop.
def fetch_audio_features(sp, username, playlist_id):
"""
Returns the selected audio features of every track,
for the given playlist.
"""
# Use the fetch_playlist_tracks function to fetch all of the tracks
playlist = fetch_playlist_tracks(sp, username, playlist_id)
index = 0
audio_features = []
# Make the API request
while index < playlist.shape[0]:
audio_features += sp.audio_features(playlist.iloc[index:index + 50, 0])
index += 50
# Append the audio features in a list
features_list = []
for features in audio_features:
features_list.append([features['danceability'],
features['energy'], features['tempo'],
features['loudness'], features['valence']])
df_audio_features = pd.DataFrame(features_list, columns=['danceability', 'energy',
'tempo', 'loudness', 'valence'])
# Set the 'tempo' & 'loudness' in the same range with the rest features
for feature in df_audio_features.columns:
if feature == 'tempo' or feature == 'loudness':
continue
df_audio_features[feature] = df_audio_features[feature] * 100
# Create the final df, using the 'track_id' as index for future reference
df_playlist_audio_features = pd.concat([playlist, df_audio_features], axis=1)
df_playlist_audio_features.set_index('track_id', inplace=True, drop=True)
return df_playlist_audio_features
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment