numpy中的“IndexError: too many indices”
我知道很多人问过这个问题,但我找不到一个合适的答案来解决我的问题。
我有一个数组 X::
X=
[1. 2. -10.]
现在我想根据这个 X 数组创建一个矩阵 Y。我的代码是::
# 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 行。如果我把数组 X 改成 2 行或更多行,就不会出现错误。只有当 X 数组只有 1 行时,才会报错。现在,在我的情况下,数组 X 可以有任意行数。它可以有 1 行、5 行或 100 行。我想写一段代码,能够处理任何行数的数组 X,而不会出现错误。我该如何解决这个问题呢?
提前谢谢你....
1 个回答
6
我建议使用 numpy.matrix
,而不是 ndarray
,因为它无论你有多少行,始终保持二维的结构:
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