4

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
  • 1
    It sounds like when you say "1 row", you really mean it doesn't have the "rows" dimension at all. Can you change your code so it does have that dimension? Commented Mar 1, 2014 at 1:34

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Or if you don't want the added behavior of the np.matrix (like * doing matrix multiplication), just use x = np.atleast_2d(x).
@askewchan thx! forgot it since I seldom use that... updated ;)
ahh.... thank you. I just converted numpy array X to numpy matrix X. Now its working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.