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

如何解决Pandas KeyError:df长度为5000但df.loc[809]触发键错误

问题原因分析
  • random.randint(0, len(df))会生成包含两端值的随机整数,当生成的索引等于len(df)时,这个索引超出了DataFrame的有效索引范围(默认索引是从0到len(df)-1),因此触发KeyError。
  • 你的代码两次调用df.loc[index],存在重复计算,可优化为一次访问。
解决方案

方案1:修正随机索引范围

把random.randint的上限改为len(df)-1,确保生成的索引始终在有效范围内:

import random
index = random.randint(0, len(df)-1)
song = [df.loc[index, 'Artist'], df.loc[index, 'Song']]
print(song)

方案2:使用Pandas内置随机采样方法(更简洁可靠)

直接用df.sample()随机选取一行,无需手动处理索引,尤其适合非默认整数索引的DataFrame:

random_row = df.sample(n=1).iloc[0]
song = [random_row['Artist'], random_row['Song']]
print(song)

也可以写成更紧凑的形式:

song = df.sample(n=1)[['Artist', 'Song']].values.flatten().tolist()
print(song)

额外优化建议

  • 避免多次调用df.loc[index],改为一次性指定列名df.loc[index, ['Artist', 'Song']],减少重复计算开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:45:25