简体   繁体   English

Python - 使用函数和创建数据框

[英]Python - Using functions and creating dataframes

I am fairly new to python and I have started working/creating different projects.我对 python 相当陌生,我已经开始工作/创建不同的项目。

In a project I'm using Spotipy to grab an artists discography.在一个项目中,我使用 Spotipy 来获取艺术家唱片。 I have the code below that grabs the artist information and calls another function show_album_tracks我有下面的代码来获取艺术家信息并调用另一个函数show_album_tracks

def show_artist_albums(id):
    albums = []
    results = sp.artist_albums(artist['id'], album_type='album')
    albums.extend(results['items'])
    while results['next']:
        results = sp.next(results)
        albums.extend(results['items'])
    print('Total albums:', len(albums))
    unique = set()  # skip duplicate albums
    for album in albums:
        name = album['name'].lower()
        if name not in unique:
            print(name)
            unique.add(name)
            show_album_tracks(album)

In show_album_tracks it prints the below track list在 show_album_tracks 中,它会打印以下曲目列表

def show_album_tracks(album):
    tracks = []
    results = sp.album_tracks(album['id'])
    #print(results)
    tracks.extend(results['items'])
    while results['next']:
        results = sp.next(results)
        tracks.extend(results['items'])
    for track in tracks:
        print('  ', track['name'])
        print()
        print(track)

So tracks contains the information I would like to put into a csv.所以tracks包含我想放入 csv 的信息。 Whats the best method for exporting?什么是出口的最佳方法? I tried creating a dataframe within the function but it prints out empty.我尝试在函数中创建一个数据框,但它打印出来是空的。 Any help is appreciated.任何帮助表示赞赏。 Any other links to help read and understand the structure is appreciated as well任何其他有助于阅读和理解结构的链接也值得赞赏

see the output snippet below:请参阅下面的输出片段:

{'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/06HL4z0CvFAxyc27GXpf02'}, 'href': 'https://api.spotify.com/v1/artists/06HL4z0CvFAxyc27GXpf02', 'id': '06HL4z0CvFAxyc27GXpf02', 'name': 'Taylor Swift', 'type': 'artist', 'uri': 'spotify:artist:06HL4z0CvFAxyc27GXpf02'}], 'available_markets': ['AD', 'AE', 'AR', 'AT', 'AU', 'BE', 'BG', 'BH', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EC', 'EE', 'EG', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'JO', 'JP', 'KW', 'LB', 'LI', 'LT', 'LU', 'LV', 'MA', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'OM', 'PA', 'PE', 'PH', 'PL', 'PS', 'PT', 'PY', 'QA', 'RO', 'SA', 'SE', 'SG', 'SK', 'SV', 'TH', 'TN', 'TR', 'TW', 'US', 'UY', 'VN', 'ZA'], 'disc_number': 1, 'duration_ms': 170640, 'explicit': False, 'external_urls': {'spotify': 'https://open.spotify.com/track/43rA71bccXFGD4C8GOpIlN'}, 'href': 'https://api.spotify.com/v1/tracks/43rA71bccXFGD4C8GOpIlN', 'id': '43rA71bccXFGD4C8GOpIlN', 'is_local': False, 'name': 'I Forgot That You Existed', 'preview_url': None, 'track_number': 1, 'type': 'track', 'uri': 'spotify:track:43rA71bccXFGD4C8GOpIlN'}
   Cruel Summer

{'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/06HL4z0CvFAxyc27GXpf02'}, 'href': 'https://api.spotify.com/v1/artists/06HL4z0CvFAxyc27GXpf02', 'id': '06HL4z0CvFAxyc27GXpf02', 'name': 'Taylor Swift', 'type': 'artist', 'uri': 'spotify:artist:06HL4z0CvFAxyc27GXpf02'}], 'available_markets': ['AD', 'AE', 'AR', 'AT', 'AU', 'BE', 'BG', 'BH', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EC', 'EE', 'EG', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'JO', 'JP', 'KW', 'LB', 'LI', 'LT', 'LU', 'LV', 'MA', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'OM', 'PA', 'PE', 'PH', 'PL', 'PS', 'PT', 'PY', 'QA', 'RO', 'SA', 'SE', 'SG', 'SK', 'SV', 'TH', 'TN', 'TR', 'TW', 'US', 'UY', 'VN', 'ZA'], 'disc_number': 1, 'duration_ms': 178426, 'explicit': False, 'external_urls': {'spotify': 'https://open.spotify.com/track/1BxfuPKGuaTgP7aM0Bbdwr'}, 'href': 'https://api.spotify.com/v1/tracks/1BxfuPKGuaTgP7aM0Bbdwr', 'id': '1BxfuPKGuaTgP7aM0Bbdwr', 'is_local': False, 'name': 'Cruel Summer', 'preview_url': None, 'track_number': 2, 'type': 'track', 'uri': 'spotify:track:1BxfuPKGuaTgP7aM0Bbdwr'}
   Lover

If you post your output it would be easy to identify.如果您发布输出,则很容易识别。 but any way you can try below code但任何方式你都可以尝试下面的代码

 csv_file = open(output_file, "w")
 writer = csv.writer(csv_file, delimiter=',', lineterminator="\n", 
                      quoting=csv.QUOTE_NONNUMERIC)
 for track in tracks:
   writer.writerow(track)

or directly you can append to list或者直接添加到列表

 writer.writerow(tracks)

The easiest option to manage dataframes is Pandas.管理数据框最简单的选择是 Pandas。

I dont know what do you have in your lists.我不知道你的清单上有什么。 In any case pandas allow you to create dataframes from lists:在任何情况下,pandas 都允许您从列表中创建数据框:

import pandas as pd
dataframe = pd.DataFrame([1,2,3],[4,5,6]], columns=['col1', 'col2', 'col3'])

   col1  col2  col3
0     1     2     3
1     4     5     6

Where I wrote the lists you should insert your own lists.在我编写列表的地方,您应该插入自己的列表。 Every list as you can see makes a row, but you can also add them as columns:您可以看到每个列表都排成一行,但您也可以将它们添加为列:

df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
                   'mask': ['red', 'purple'],
                   'weapon': ['sai', 'bo staff']})

Then if you want to export it as csv you only have to use the method to_csv()然后,如果要将其导出为 csv,则只需使用to_csv()方法

You can pass the method arguments to write it directly to your disk: pandas doc您可以传递方法参数以将其直接写入磁盘: pandas doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM