0

我编写了一个代码来将 spotipy 的输出存储到 pd.Dataframe 中:

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)

但是那里有很多我不需要的输出,所以我找到了一个只输出我需要的数据的代码:

for i, item in enumerate(playlist['items']):
    track = item['track']
    need = (i, track['artists'][0]['name'], track['name'], track['id'])

现在我可以使用 print(need) 来准确输出我想要的内容,但我不知道如何将数据存储到 DataFrame 中。

如果有人可以帮助我,那就太好了。

谢谢你。

4

1 回答 1

0

附加您需要分隔列表的输出,然后将这些列表加载到数据框中:

# appending needed data to separate lists

for i, item in enumerate(playlist['items']):
    track = item['track']
    artist_name.append(track['artists'][0]['name'])
    track_name.append(track['name'])
    track_id.append(track['id']

# loading lists into the dataframe

df = pd.DataFrame({'artist_name':artist_name,'track_name':track_name,'track_id':track_id})
于 2018-04-23T12:24:25.663 回答