user31415926
user31415926

Reputation: 33

How to index a 1D numpy array as if it is a matrix with 1 row?

I have a 1D numpy array like:

a = np.array([1,2,3,4,5])

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

Upvotes: 0

Views: 78

Answers (3)

kmario23
kmario23

Reputation: 61325

Also, you can use these as well:

In [7]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [8]: a = a[np.newaxis, :]

In [9]: a[0,2]
Out[9]: 3


# another approach using `None`    
In [10]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [11]: a = a[None, :]

In [12]: a[0, 2]
Out[12]: 3

When you use np.newaxis or None once, a new axis is added; Note that you've assign this to your original array to make modification to the final array.

Upvotes: 0

unutbu
unutbu

Reputation: 879181

You could use np.atleast_2d to promote 1D arrays to 2D:

a = np.atleast_2d(a)

If you put this inside of your loop then you can henceforth treat all as as 2D (or higher-dimensional) arrays.


For example,

In [103]: a1 = np.array([1,2,3,4,5])
In [105]: np.atleast_2d(a1)
Out[107]: array([[1, 2, 3, 4, 5]])

while higher-dimensional arrays are unchanged:

In [104]: a2 = np.array([[1,2],[3,4]])
In [108]: np.atleast_2d(a2)
Out[108]: 
array([[1, 2],
       [3, 4]])

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95872

Use .reshape and pass -1 as the second argument:

>>> a = np.array([1,2,3,4,5])
>>> a = a.reshape(1, -1)
>>> a[0,2]
3

Note, if you are expecting any type of ndarray, then this might not be what you want:

>>> arr = np.array([[1,2],[3,4]])
>>> arr
array([[1, 2],
       [3, 4]])
>>> arr.reshape(1, -1)
array([[1, 2, 3, 4]])

So you may need to add a conditional check:

>>> if a.ndim < 2:
...     a = a.reshape(1, -1)
...
>>> a
array([[1, 2, 3, 4, 5]])

Upvotes: 1

Related Questions