XYZT
XYZT

Reputation: 674

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?

Upvotes: 6

Views: 3802

Answers (2)

Samufi
Samufi

Reputation: 2710

To abbreviate the expression (and make it work for arbitrary dimensions chosen at runtime), you could just generate the index on the fly:

x = x[(slice(None),)+(None,)*9]

If you want to put your slice to a different position, the index tuple can be adjusted accordingly.

Note, there will be no benefit regarding performance. This is just more concise writing and may be even less readable than writing out the Nones

Furthermore, the reshape solution has similar performance.

Upvotes: 0

Divakar
Divakar

Reputation: 221524

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)

Upvotes: 5

Related Questions