最受歡迎的歌曲
你還有一個 Spotify 資料的任務:找出所有可用年份中最受歡迎的前 10 首歌曲。你需要的演算法是:先對每一年各自找出前 10 首,接著把這些結果合併,再從其中選出整體的前 10。
下列函式會在一個 DataFrame 中找出前 10 首歌曲,已為你提供並可在你的環境中使用。
def top_10_most_popular(df):
return df.nlargest(n=10, columns='popularity')
dask 與 delayed() 函式已為你匯入。pandas 已以 pd 匯入。檔名的清單在你的環境中名為 filenames,每個檔案所對應的年份則存放在 years 這個 list 中。
本練習屬於課程
在 Python 中使用 Dask 進行平行程式設計
練習說明
- 對每個檔案,使用
top_10_most_popular()函式找出該年度的前 10 首歌曲。 - 對每年得到的前 10 清單呼叫
dask.compute(),並從回傳的 tuple 中取出第一個元素。 - 對合併後的 DataFrame 再次執行
top_10_most_popular(),找出整體的前 10 首歌曲。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
top_songs = []
for file in filenames:
df = delayed(pd.read_csv)(file)
# Find the top 10 most popular songs in this file
df_top_10 = ____
top_songs.append(df_top_10)
# Compute the list of top 10s
top_songs_list = ____
# Concatenate them and find the best of the best
top_songs_df = pd.concat(top_songs_list)
df_all_time_top_10 = ____
print(df_all_time_top_10)