【问题标题】:IndexError when using iloc使用 iloc 时出现 IndexError
【发布时间】:2021-10-12 15:45:33
【问题描述】:

我目前正在浏览数据框的索引,然后尝试使用该索引选择一行。代码如下。

for index in clean_data.index:
    data_row = clean_data.iloc[[indx]]

但是,我得到了错误:

IndexError: positional indexers are out-of-bounds

我的数据框结构如下:

   game_week  game_day  game_month
1          2        15           1
2          3        17           1

代码可以很好地处理第一个索引,但在处理索引值为 2 时会引发错误。

由于在我的其余代码中需要索引,我不能使用 iterrows 或 itertuples。
我还需要将格式保留为数据框,这就是我在列表中提供索引的原因。 (否则它会返回一个系列)

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    通过迭代索引,您使用的是索引键,而不是绝对位置。将iloc 替换为loc 或迭代range(len(clean_data.index))

    只有当索引为 n 行的 0,1,2,…,n-1 时,您所做的才有效。在您的示例中不是这种情况,它有 1,2 作为键(不是 0,1)

    这是一个实际的例子:

    >>> df = pd.DataFrame(list('ABC'), index=[2,1,7])
    >>> df
       0
    2  A
    1  B
    7  C
    
    for index in df.index:
        print(df.loc[[index]])
    

    for index in range(len(df)):
        print(df.iloc[[index]])
    

    两个输出:

       0
    2  A
       0
    1  B
       0
    7  C
    

    但是:

    for index in df.index:
        print(df.iloc[[index]])
    

    输出:

    IndexError: positional indexers are out-of-bounds
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 2017-11-15
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2018-03-15
      • 1970-01-01
      相关资源
      最近更新 更多