“IndexError: too many indices” in numpy python

2020-02-29 06:39发布

问题:

I know many people asked this question, but I could not get an appropriate answer that can solve my problem.

I have an array X::

    X=
    [1. 2. -10.]

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

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?

Thanks in advance....

回答1:

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 for @askewchan mentioning, if you want to use the numpy array arithmetic, use np.atleast_2d:

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