最受欢迎的歌曲
在这份 Spotify 数据上,您还有一个任务:找出所有可用年份中最受欢迎的前 10 首歌曲。您需要使用的算法是:先计算每个年份的前 10 首歌曲,然后将这些结果合并,再从合并后的结果中找出"前 10 的前 10"。
下面这个用于在 DataFrame 中找出前 10 首歌曲的函数已经为您提供,并可在您的环境中直接使用。
def top_10_most_popular(df):
return df.nlargest(n=10, columns='popularity')
dask 和 delayed() 函数已为您导入。pandas 已以 pd 导入。文件名列表在您的环境中名为 filenames,每个文件对应的年份存储在列表 years 中。
本练习是课程的一部分
Python 中的 Dask 并行编程
练习说明
- 对每个文件,使用
top_10_most_popular()函数找出该年份的前 10 首歌曲。 - 计算各年份"前 10"的列表,并从返回的元组中取出第一个元素。
- 对拼接后的 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)