NumPy数组IndexError:索引99超出了大小为1的轴0的范围

时间:2019-04-20 11:49:46

标签: python python-3.x numpy

我正在使用Python 3.6,尝试使用NumPy数组引用时出现索引错误。

这是我的代码:

import numpy as np

length1 = 35
length2 = 20
siglength = 10

csrf = np.array([])

sm = 2.0 / 35
sm2 = 2.0 / 20

for n in range(0, 198) :

    if n == 0 :
        i = 100
        t = i - 100
        setcsf = t - 0 * sm + 0
        csrf = np.append(csrf, setcsf)

    else :
        i = (close[n] / close[int(n+1)]) * 100
        t = i - 100
        setcsf = t - csrf[int(i-1)] * sm + csrf[int(i-1)]
        csrf = np.append(csrf, setcsf)
print(csrf)

但是结果是:

Traceback (most recent call last):
File "test.py", line 64, in <module>
setcsf = t - csrf[int(i-1)] * sm + csrf[int(i-1)]
IndexError: index 99 is out of bounds for axis 0 with size 1

我认为问题出在第64行setcsf = t - csrf[int(i-1)] * sm + csrf[int(i-1)],但我绝对不知道如何修改代码并替换它。

1 个答案:

答案 0 :(得分:0)

是的,该错误是由于您的线路

setcsf = t - csrf[int(i-1)] * sm + csrf[int(i-1)]

错误消息

IndexError: index 99 is out of bounds for axis 0 with size 1

表示您尝试在大小为1的轴0(唯一的轴)上访问索引int(i-1)的索引99(csrf的值为99),因此唯一的索引可能是被访问为0。

此外,您的示例代码不是Minimal, Complete, and Verifiable example。变量close来自哪里?

也许您想使用n而不是i,就像下面的一行一样?

setcsf = t - csrf[int(n-1)] * sm + csrf[int(n-1)]

这将是有道理的,因为n-1将始终引用前一个循环运行的索引。您不会得到IndexError

或者您可能想预先用值初始化csrf

csrf = np.array([0] * 198)