Indexing a one-dimensional numpy.array as a matrix

I am trying to index numpy.array with various measurements at runtime. For extraction, for example. the first line of the array n * m a , you can just do

 a[0,:] 

However, if a is a 1xn vector, this code above returns an index error:

IndexError: Too Many Indexes

Since the code should be executed as efficiently as possible, I do not want to enter an if . Does anyone have a convenient solution that is ideally not related to changing data types?

+7
source share
2 answers

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

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

+9
source

From 'array' or 'matrix'? What should i use? in the Numpy section for Matlab wiki users :

For an array, 1xN, Nx1, and N vector shapes are two different things. Operations of type A [:, 1] return an array of rank 1 of form N, and not rank-2 of form Nx1. Transposing in a rank-1 array does nothing.

Here is an example showing that they do not match:

 >>> 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 your arrays are 2d arrays or some of them are 1d arrays?

If you want to use the array[0,:] command, I would recommend using 1xN 2d arrays instead of 1d arrays. Here is 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]) 
+1
source

All Articles