python - NumPy 数组索引错误 : index 99 is out of bounds for axis 0 with size 1

标签 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)],但我绝对不知道如何修改代码并替换它。

最佳答案

是的,错误是由于您的线路造成的

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

错误信息

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

表示您尝试访问轴 0(其唯一轴)上 csrf 的索引 99(int(i-1) 的值为 99),但它只有一个大小为 1,因此您可以访问的唯一索引将为 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)

关于python - NumPy 数组索引错误 : index 99 is out of bounds for axis 0 with size 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773236/

相关文章:

python - python字典的编码指南

python - Python 中的 'class A:' 和 'class A(object):' 有什么区别?

python - 如何在用python编写的解释器中实现多重赋值?

python - 如何/在哪里定义/传递cloudformation参数?

python - 以特定频率扩展数据框 - Python

python - numpy.unravel_index 不返回预期的行索引

python - 如何避免创建具有相同值的对象?

python: "with"用两个函数打开文件的语法

python - Django 事务不起作用

python - 使用 np.einsum 进行光线转换的矢量化范围