How to transpose numpy ndarray in place?

Viewed 3614

I'm using numpy.

I have an ndarray with shape of [T, H, W, C] and I want to transpose it to become like: [T, C, H, W]. However, this array is huge and I want to be memory-efficient.

But I just found np.transpose to do this which is not in-place.

Why do operations like np.transpose don't have their in-place counterpart?

I used to think that any operation named np.Bar would have its in-place counterpart named np.Bar_, only to find that this is not the truth.

1 Answers

From np.transpose docs

A view is returned whenever possible.

meaning no extra memory is allocated for the output array.

>>> import numpy as np

>>> A = np.random.rand(2, 3, 4, 5)
>>> B = np.transpose(A, axes=(0, 3, 1, 2))

>>> A.shape
(2, 3, 4, 5)
>>> B.shape
(2, 5, 3, 4)

You can use np.shares_memory to check if B is a view of A:

>>> np.shares_memory(A, B)
True

So, you can safely transpose your data withnp.transpose.

Related