Last active
March 8, 2020 12:43
-
-
Save makispl/d8e3be4b51a8e4e9b9d8e11e668daa21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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