【问题标题】:Avoiding indexing error when referencing next index while iterating在迭代时引用下一个索引时避免索引错误
【发布时间】:2018-07-03 16:50:46
【问题描述】:

所以我有一个 pandas 数据框,我正在使用 iterrows() 来迭代每一行,并对其进行一些复杂的操作。其中一部分涉及从下一行的坐标中减去当前行的坐标,所以我这样做了

sqrt(((row[5] - df.iloc[index+1, 5])**2) + ((row[4] - df.iloc[index+1, 4])**2)) < .1

问题是当我完成对所有行的迭代时,最后一行会给我一个索引错误,因为我将引用下一个不存在的索引。我正在考虑在数据框的末尾添加一个虚拟行。有没有更优雅的解决方案来解决这个问题?

编辑:

for index, row in df.iterrows():
    if row[8] < 10 and sqrt(((row[5] - df.iloc[index+1, 5])**2) + ((row[4] - df.iloc[index+1, 4])**2)) < .1
        #do stuff

【问题讨论】:

  • 使用shift而不是index+1。
  • 您可以检查是否i == total_number_of_rows-1,如果是,请使用df.iloc[index, ..] 而不是df.iloc[index+1, ..]。否则,你就做df.iloc[index+1, ..]
  • @Scott Boston 所以这只是 df.shift.iloc[index, 5]?
  • 能否添加更完整的代码问题,索引是如何定义的?
  • 已在上面编辑。索引来自 iterrows()。

标签: python pandas indexing


【解决方案1】:

当行是最后一行时,您的代码尝试访问不存在的 (row+1),这就是您收到索引错误的原因。

运行一个循环来遍历除最后一行之外的所有行,然后当您的代码到达倒数第二行时,它将访问最后一行。

试试这个代码

for i in range(len(df.index)-1):           #runs from row 0 to n-2 rows if total rows are n
    # your code
    sqrt(((row[5] - df.iloc[index+1, 5])**2) + ((row[4] - df.iloc[index+1, 4])**2)) < .1

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2020-08-12
    • 2019-12-12
    • 2014-09-19
    • 2018-07-16
    • 2022-12-20
    相关资源
    最近更新 更多