" IndexError:太多的指数"在numpy的蟒蛇 [英] "IndexError: too many indices" in numpy python
问题描述
我知道很多人问过这个问题,但我无法获得可以解决我的问题一个合适的答案。
I know many people asked this question, but I could not get an appropriate answer that can solve my problem.
我有一个数组X ::
I have an array X::
X=
[1. 2. -10.]
现在我试图做一个矩阵Y读该X阵列。我的code是:
Now I am trying to make a matrix Y reading this X array. My code is::
# 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)
现在,如果我运行它,它提供了以下错误:
Now if I run this, it gives following error::
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行。我想写一个code能与没有任何错误任意数量的行读取阵列的X.我怎样才能解决这个问题?
here, my array has only 1 row. If I make array X with 2 or more rows, it does not give me any error. It gives me error only when X array has 1 row. Now, in my case, array X can have any number of rows. It can have 1 row or 5 rows or 100 rows. I want to write a code which can read array X with any number of rows without any error. How can I solve this problem?
在此先感谢....
推荐答案
我建议使用 numpy.matrix
而不是 ndarray
,它保持的2维,无论你有多少行:
I suggest using numpy.matrix
instead of ndarray
, it keeps a dimension of 2 regardless of how many rows you have:
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
THX为@askewchan提的是,如果你想使用numpy的数组运算,使用 np.atleast_2d
:
In [85]: np.atleast_2d(x[1])[0, 1]
Out[85]: 4
这篇关于&QUOT; IndexError:太多的指数&QUOT;在numpy的蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!