Python Forum

Full Version: Using Pandas to store spotipy output in csv (python)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I want to use spotipy to collect data from the spotify API.
I was able to make it work with:


import pandas as pd
import spotipy
sp = spotipy.Spotify()

from spotipy.oauth2 import SpotifyClientCredentials 

cid ='XXXCIDXXX' 
secret = 'XXXSECRETXXX' 
client_credentials_manager = SpotifyClientCredentials(client_id=cid, 
client_secret=secret) 
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 
sp.trace=False 

playlist = sp.user_playlist_tracks('spotify', '37i9dQZF1DX5nwnRMcdReF') 
songs = playlist['items']

df = pd.DataFrame(songs)

df.to_csv('Songs.csv', sep=';', encoding='utf-8', index=True)
This Outputs a a lot of data that i dont Need.
I found a code to only output the data that I need which is:

for i, item in enumerate(playlist['items']):
    track = item['track']
    need = (i, track['artists'][0]['name'], track['name'], track['id'])
now i can use print(need) to output exactly what I want, but I dont know how to store the data into the DataFrame.

If someone could help me that would be great.

Thank you.
Try make a new Dataframe based on the loop.
Then write that Dataframe to csv new_df.to_csv
Untested example:
need = []
for i, item in enumerate(playlist['items']):
    track = item['track']
    need.append((i, track['artists'][0]['name'], track['name'], track['id']))

new_df = pd.DataFrame(need, columns=('Item', 'Artists', 'Name', 'Id'))
Hi Snippsat,

It works. Thank you very much :-)