Home > Software design >  How to return 1 in numpy array with one row using .shape?
How to return 1 in numpy array with one row using .shape?

Time:01-23

For the arrays with only one row x_data.shape return (4,) or (5,) is it possible to modify it to return (4,1)? Sometimes when I pass one dimension matrix to my function it runs into an error because m = x_data.shape[1] is not defined.

CodePudding user response:

You can use the expand_dims() NumPy function:

import numpy as np

a = np.array([1, 2, 3, 4])
print(a.shape)  # (4,)
a = np.expand_dims(a, 1)
print(a.shape)  # (4, 1)
print(a)  # column vector

Note that (4, 1) is a column vector. You can get a row vector of shape (1, 4) by using np.expand_dims(a, 0).

CodePudding user response:

There are lots of ways:

In [1]: x=np.arange(4); x
Out[1]: array([0, 1, 2, 3])

reshape is a good function/method to learn well:

In [2]: x.reshape(-1,1)
Out[2]: 
array([[0],
       [1],
       [2],
       [3]])
In [4]: x.reshape(1,-1)
Out[4]: array([[0, 1, 2, 3]])

Many experienced users like to np.newaxis/None indexing:

In [5]: x[:,None]
Out[5]: 
array([[0],
       [1],
       [2],
       [3]])
In [6]: x[None,:]
Out[6]: array([[0, 1, 2, 3]])

Functions like expand_dims use reshape - look at its code:

In [8]: np.expand_dims(x,1)
Out[8]: 
array([[0],
       [1],
       [2],
       [3]])

Another:

In [9]: np.atleast_2d(x)
Out[9]: array([[0, 1, 2, 3]])

And if making the array from 'scratch', ndmin can be used:

In [10]: np.array(x, ndmin=2)
Out[10]: array([[0, 1, 2, 3]])

Because leading dimensions are "outermost" (for C order), a (1,4) shape is in some sense more "natural" for numpy than (4,1).

  • Related