numpy python中的“ IndexError:索引过多”
问题内容:
我知道很多人都问过这个问题,但是我无法获得能够解决我的问题的适当答案。
我有一个数组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行。如果我使数组X具有2行或更多行,它不会给我任何错误。仅当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提到的Thx,如果要使用numpy数组算法,请使用np.atleast_2d
:
In [85]: np.atleast_2d(x[1])[0, 1]
Out[85]: 4