Pandas KeyError错误修复:len(df) = 5000,但df.loc[809]导致KeyError。

huangapple go评论58阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月6日 20:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定