Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array?

What I am trying to do right now is:

x = x[:, None,  None,  None,  None,  None,  None,  None,  None,  None]

Basically, I want to expand my Numpy array by 9 dimensions. Or some N number of dimensions where N might not be known in advance!

Is there a better way to do this?

like image 682
XYZT Avatar asked Oct 16 '16 10:10

XYZT


1 Answers

One alternative approach could be with reshaping -

x.reshape((-1,) + (1,)*N)  # N is no. of dims to be appended

So, basically for the None's that correspond to singleton dimensions, we are using a shape of length 1 along those dims. For the first axis, we are using a shape of -1 to push all elements into it.

Sample run -

In [119]: x = np.array([2,5,6,4])

In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)
like image 199
Divakar Avatar answered Sep 27 '22 23:09

Divakar