python - numpy python 中的 "IndexError: too many indices"

标签 python arrays numpy indexing

我知道很多人问过这个问题,但我找不到合适的答案来解决我的问题。

我有一个数组 X::

    X=
    [1. 2. -10.]

现在我正在尝试创建一个矩阵 Y 来读取这个 X 数组。我的代码是::

#   make Y matrix

Y=np.matrix(np.zeros((len(X),2)))
i=0

while i < len(load_value):
    if X[i,1] % 2 != 0:
        Y[i,0] = X[i,0]*2-1
    elif X[i,1] % 2 == 0:
        Y[i,0] = X[i,0] * 2
    Y[i,1] = X[i,2]
    i = i + 1
print('Y=')
print(Y)

现在如果我运行它,它会给出以下错误::

    Traceback (most recent call last):
      File "C:\Users\User\Desktop\Code.py", line 251, in <module>
        if X[i,1] % 2 != 0:
    IndexError: too many indices

在这里,我的数组只有 1 行。如果我用 2 行或更多行创建数组 X,它不会给我任何错误。只有当 X 数组有 1 行时它才会给我错误。现在,在我的例子中,数组 X 可以有任意数量的行。它可以有 1 行或 5 行或 100 行。我想编写一个代码,它可以读取任意行数的数组 X 而不会出现任何错误。我该如何解决这个问题?

提前致谢....

最佳答案

我建议使用 numpy.matrix 而不是 ndarray,无论您有多少行,它都会保持 2 维:

In [17]: x
Out[17]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [18]: m=np.asmatrix(x)

In [19]: m[1]
Out[19]: matrix([[3, 4, 5]])

In [20]: m[1][0, 1]
Out[20]: 4

In [21]: x[1][0, 1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-21-bef99eb03402> in <module>()
----> 1 x[1][0, 1]

IndexError: too many indices

感谢 @askewchan 提到,如果你想使用 numpy 数组算法,请使用 np.atleast_2d:

In [85]: np.atleast_2d(x[1])[0, 1]
Out[85]: 4

关于python - numpy python 中的 "IndexError: too many indices",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22108909/

相关文章:

python - UnicodeEncodeError,需要修复

python - 具有不同 x 和 y 编码的 Altair 选择

java - 如何在一个数组中使用不同类的对象?(Java)

java - 有没有办法在java中使用图形按钮设置数组的值?

python - 为什么以下对象是 numpy 字符串而不是 datetime.datetime 对象?

python - 为什么 hstack() 复制数据而 hsplit() 在其上创建 View ?

python - 沿轴连接 numpy 字符串数组?

Python Selenium 本地存储返回 None

python - Python DB-API 2.0 仅适用于关系数据库吗?

javascript - 嵌套循环未形成完整对象 - 问题