7

I am trying to index a numpy.array with varying dimensions during runtime. To retrieve e.g. the first row of a n*m array a, you can simply do

a[0,:]

However, in case a happens to be a 1xn vector, this code above returns an index error:

IndexError: too many indices

As the code needs to be executed as efficiently as possible I don't want to introduce an if statement. Does anybody have a convenient solution that ideally doesn't involve changing any data structure types?

3
  • You only have 1- and 2D arrays? Commented Jan 17, 2011 at 18:50
  • Would simply reshaping the array to be a 2d 1xn array instead of a 1d n-length array count as "changing the data structure type"? Commented Jan 17, 2011 at 18:51
  • All these are 2D arrays (mxn) theoretically, some just happend to be 1xn arrays, e.g. m=1. In fact they represent conditional probability tables and the case m=1 corresponds to a variable that doesn't have any dependencies. Commented Jan 17, 2011 at 18:56

2 Answers 2

9

Just use a[0] instead of a[0,:]. It will return the first line for a matrix and the first entry for a vector. Is this what you are looking for?

If you want to get the whole vector in the one-dimensional case instead, you can use numpy.atleast_2d(a)[0]. It won't copy your vector -- it will just access it as a two-dimensional 1 x n-array.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know about atleast_2d; handy. +1
I can second that, numpy.atleast_2d is very helpful and exactly what I was looking for. Thanks a lot.
1

From the 'array' or 'matrix'? Which should I use? section of the Numpy for Matlab Users wiki page:

For array, the vector shapes 1xN, Nx1, and N are all different things. Operations like A[:,1] return a rank-1 array of shape N, not a rank-2 of shape Nx1. Transpose on a rank-1 array does nothing.

Here's an example showing that they are not the same:

>>> import numpy as np
>>> a1 = np.array([1,2,3])
>>> a1
array([1, 2, 3])
>>> a2 = np.array([[1,2,3]])    // Notice the two sets of brackets
>>> a2
array([[1, 2, 3]])
>>> a3 = np.array([[1],[2],[3]])
>>> a3
array([[1],
       [2],
       [3]])

So, are you sure that all of your arrays are 2d arrays, or are some of them 1d arrays?

If you want to use your command of array[0,:], I would recommend actually using 1xN 2d arrays instead of 1d arrays. Here's an example:

>>> a2 = np.array([[1,2,3]])    // Notice the two sets of brackets
>>> a2
array([[1, 2, 3]])
>>> a2[0,:]
array([1, 2, 3])
>>> b2 = np.array([[1,2,3],[4,5,6]])
>>> b2
array([[1, 2, 3],
       [4, 5, 6]])
>>> b2[0,:]
array([1, 2, 3])

Comments

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.