user5730994 user5730994 - 2 years ago 66
Python Question

passing elements returned by an API to a Pandas DF

I am very new to pandas, and it looks like it is the best tool for what I have in mind. I was able to collect certain data from the soundcloud API, and print the fields want:

for track in tracks:
print track.title, "-", track.genre, "-", track.tag_list, "-", track.created_at, "-", track.last_modified, "-", \
track.permalink_url, "-", track.playback_count, "-", track.duration

Tracks, by itself returns this:

[<soundcloud.resource.Resource object at 0x10bd66e50>, <soundcloud.resource.Resource object at 0x10bd66ad0>, <soundcloud.resource.Resource object at 0x10bd66b10>, <soundcloud.resource.Resource object at 0x10bd75d50>, <soundcloud.resource.Resource object at 0x10bd75c10>

Is there an easy way to get all (or some of the components) of the tracks object (tracks, genre, etc.) in a pandas df? Do I have to print to a file or something (which I might need at a later point), and then use pd.read_csv() or a similar function?

Answer Source

You can create a DataFrame using a list comprehension.

all_tracks = pd.DataFrame(
    [(t.title, t.genre, t.tag_list, t.created_at, t.last_modified, 
      t.permalink_url, t.playback_count, t.duration) 
     for t in tracks], 
    columns=['title', 'genre', 'tag_list', 'created_at', 'last_modified',
             'permalink_url', 'playback_count', 'duration'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download