Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose numpy ndarray in place?

Tags:

python

numpy

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.

like image 262
youkaichao Avatar asked Sep 02 '18 11:09

youkaichao


People also ask

Can you transpose a NumPy array?

NumPy Matrix transpose() Python numpy module is mostly used to work with arrays in Python. We can use the transpose() function to get the transpose of an array.

How do I switch rows and columns in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.


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.

like image 72
taras Avatar answered Sep 23 '22 18:09

taras