Dims
Dims

Reputation: 51069

How to reshape only last dimensions in numpy?

Suppose I have A of shape (...,96) and want to reshape it into (...,32,3) keeping both lengths and number of preceding dimensions, if ever, intact.

How to do this?

If I write

np.reshape(A, (-1, 32, 2))

it will flatten all preceding dimensions into one single, which I don't want.

Upvotes: 8

Views: 5351

Answers (1)

Divakar
Divakar

Reputation: 221594

One way would be to compute the new shape tuple using the shape info concatenated with the new split axes lengths and then reshaping -

A.reshape(A.shape[:-1] + (32,3))

Sample runs -

In [898]: A = np.random.rand(5,96)

In [899]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[899]: (5, 32, 3)

In [900]: A = np.random.rand(10,11,5,96)

In [901]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[901]: (10, 11, 5, 32, 3)

Even works for 1D array -

In [902]: A = np.random.rand(96)

In [903]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[903]: (32, 3)

Works because the leading axes for concatenation was empty, thus using the split axes lengths only there -

In [904]: A.shape[:-1]
Out[904]: ()

In [905]: A.shape[:-1] + (32,3)
Out[905]: (32, 3)

Upvotes: 9

Related Questions