You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码出现IndexError报错求助:索引0超出轴0的大小0

问题排查与解决方案

错误原因

报错出现在这一行:

list_of_songs.append(df_final[df_final['song_id']== str(i) ]['title'].unique()[0])

当df_final[df_final['song_id']== str(i)]返回空DataFrame时,['title'].unique()会得到一个空数组,此时访问索引[0]就会触发IndexError。

可能的触发场景:

  • top_n_songs返回的索引i对应的歌曲ID,在df_final中不存在
  • 盲目将i转成字符串str(i),但df_final['song_id']的类型是整数,导致匹配失败(比如i是123,转成"123"后和df里的123不相等)

分步修复

1. 定位问题ID

在循环里加日志,找出哪些i没有匹配到结果:

res = list(top_n_songs(final_play, 10, 100))
list_of_songs = []
for i in res:
    # 先获取匹配结果
    match = df_final[df_final['song_id'] == str(i)]
    if match.empty:
        print(f"警告:未找到song_id为 {str(i)} 的歌曲")
        continue
    # 再取标题
    title = match['title'].unique()[0]
    list_of_songs.append(title)
print(list_of_songs)

运行后就能看到哪些ID出问题,针对性排查。

2. 修复类型不匹配问题

先检查final_play的索引类型和df_final['song_id']的类型是否一致:

# 查看final_play的索引类型
print(type(final_play.index[0]))
# 查看df_final['song_id']的类型
print(type(df_final['song_id'].iloc[0]))

如果两者类型一致(比如都是整数),就不需要转成字符串,直接用i匹配:

match = df_final[df_final['song_id'] == i]

3. 更高效的写法(替代循环)

用pandas的merge操作一次性关联数据,避免循环和索引错误:

import pandas as pd

# 先获取top N的song_id列表
top_ids = top_n_songs(final_play, 10, 100)
# 转成DataFrame方便关联
top_df = pd.DataFrame({'song_id': top_ids})
# 关联df_final获取标题,自动过滤无匹配的项
list_of_songs = top_df.merge(df_final[['song_id', 'title']], on='song_id', how='left')['title'].dropna().tolist()

4. 给top_n_songs加安全校验

避免函数返回空列表导致后续循环无意义:

def top_n_songs(data, n, min_play_counts=100):
    recommendations = data[data['play_freq'] > min_play_counts]
    if recommendations.empty:
        print(f"警告:没有播放量超过{min_play_counts}的歌曲")
        return []
    recommendations = recommendations.sort_values(by='avg_count', ascending=False)
    return recommendations.index[:n]

内容的提问来源于stack exchange,提问作者Shrikanth Krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:25:50