英文:
How to fix Pandas KeyError : len(df) = 5000, but df.loc[809] results in keyerror
问题
我正在使用索引来访问pandas中的一行,
index = random.randint(0, len(df))
song = [df.loc[index]['Artist'], df.loc[index]['Song']]
print(song)
索引始终在df的长度范围内,并且在大多数情况下运行良好,但偶尔会出现此错误,我正在努力修复它。
英文:
I am using index to access a row in pandas,
index = random.randint(0,len(df))
song = [df.loc[index]['Artist'], df.loc[index]['Song']]
print(song)
the index is always within the length of the df, and it is working well on most pulls, but from time to time i am getting this error and i am struggling to fix it
答案1
得分: 3
df.loc
使用索引(从 df.index
中获取的值),而不是行的位置。您是不是想使用 .iloc
:
index = random.randint(0, len(df))
song = [df.iloc[index]['Artist'], df.iloc[index]['Song']]
print(song)
英文:
df.loc
uses index (values from df.index
) not the position of the row. Did you mean to use .iloc
instead:
index = random.randint(0,len(df))
song = [df.iloc[index]['Artist'], df.iloc[index]['Song']]
print(song)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论