【问题标题】:How to fix Pandas KeyError : len(df) = 5000, but df.loc[809] results in keyerror如何修复 Pandas KeyError:len(df) = 5000,但 df.loc[809] 导致 keyerror
【发布时间】:2023-02-06 21:02:48
【问题描述】:

我正在使用索引访问熊猫中的一行,

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

索引始终在 df 的长度内,并且在大多数拉动上运行良好,但有时我会收到此错误并且我正在努力修复它

【问题讨论】:

    标签: python pandas keyerror


    【解决方案1】:

    df.loc 使用索引(来自df.index 的值)而不是行的位置。您是否打算改用 .iloc

    index = random.randint(0,len(df))
    song = [df.iloc[index]['Artist'], df.iloc[index]['Song']]    
    print(song)
    

    【讨论】:

    • 谢谢,牛眼
    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2019-08-23
    相关资源
    最近更新 更多