【问题标题】:if (data[i,1] == 1): IndexError: index 869 is out of bounds for axis 0 with size 869if (data[i,1] == 1): IndexError: index 869 is out of bounds for axis 0 with size 869
【发布时间】:2015-10-26 21:30:26
【问题描述】:

我有以下代码:

def findingGroups(data,i=0):
findingGroupsMatrix1=np.zeros(1)
findingGroupsMatrix2=np.zeros(1)
findingGroupsMatrix3=np.zeros(1)
findingGroupsMatrix4=np.zeros(1)
z=np.zeros(1)
print ("i",i)
while True:

    if (data[i,1] == 1):
        z[0]=i
        findingGroupsMatrix1=np.append(findingGroupsMatrix1,z,axis=0)

    elif data[i,1] == 2:
        z[0]=i
        findingGroupsMatrix2=np.append(findingGroupsMatrix2,z,axis=0)

    elif data[i,1] == 3:
        z[0]=i
        findingGroupsMatrix3=np.append(findingGroupsMatrix3,z,axis=0)

    elif data[i,1] == 4:
        z[0]=i
        findingGroupsMatrix4=np.append(findingGroupsMatrix4,z,axis=0)
    elif i == len(data):
        break
    i=i+1

这是错误:if (data[i,1] == 1): IndexError: index 869 is out of bounds for axis 0 with size 869

数据是 numpy.ndarray 和形状 (869, 10) 。你能帮我解决这个问题吗?

【问题讨论】:

  • 如果大小为 869,则表示索引 868 是最后可访问的索引,因为数组是零索引的。
  • 来自@SterlingArcher 的纯正回答
  • 你的休息测试应该是第一位的。

标签: python numpy import


【解决方案1】:

如果形状是 (869, 10),那么第一个下标从 0 到 868 运行。你的回路控制有问题。由于您知道循环执行了多少次,因此请使用“for”。为时已晚,您检查的循环。

for i in len(data):
    ....

您不必再增加 i。

另外,请注意,您仅在第二个元素不在 1-4 范围内时才检查索引。这也可能导致您的循环失败。

【讨论】:

    【解决方案2】:

    如果数组的形状是(869, 10),那么对象中的最大索引是(868, 9)(因为索引从 0 开始,这是典型的 Python 序列)。

    【讨论】:

      【解决方案3】:

      python 零索引。这意味着 869 元素数组的“第一个”元素为 0,最后一个元素为 868。因此,引用 869 将失败。下次使用搜索功能;这个问题可以通过简单地查看 python 文档或以前的问题来解决,而不是在堆栈上发布。

      【讨论】:

      • 对不起,Java..?!我的意思是你没有错,但语言不对。
      • 该程序是用 Python 编写的——它也使用基于 0 的索引。茶歇?
      • 在我看到错误 tbh 时甚至都没有阅读过这个问题,因为它太笼统了。假定java
      猜你喜欢
      • 2017-04-09
      • 2021-12-17
      • 1970-01-01
      • 2019-09-21
      • 2020-03-13
      • 2020-05-22
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多