Transpose array and actually reorder memory
Asked Answered
C

2

25

I have a 3-D NumPy array, e.g.

a = np.random.random((2,3,5))

I would like to transpose the last two axes, i.e.

b = a.transpose(0,2,1)

However, I do not want a view with twiddled strides! I want to actually copy the array and reorder it in memory. What is the best way to achieve this?

Censor answered 7/11, 2013 at 1:24 Comment(0)
O
27

The copy() method will reorder to C-contiguous order by default:

b = a.transpose(0,2,1).copy()

Be careful: the copy() function has a different default behavior. With the function, you must explicitly specify the order to ensure a C-contiguous copy:

b = np.copy(a.transpose(0,2,1), order='C')

(Note that the docstring for the function says that the ndarray method is the preferred method for creating an array copy.)

Orazio answered 7/11, 2013 at 1:29 Comment(1)
Thanks. The solution I had just found before you posted yours was b = np.zeros((2,5,3)); b[:] = a.transpose(0,2,1), but yours is much cleaner.Censor
A
5

Under the hood, the stride of b is different than a.

prefer to use ascontiguousarray, which will copy the memory when it's needed. Whereas copy will always copy memory.

Autoionization answered 22/11, 2019 at 21:58 Comment(1)
This is a very good point, especially for complicated code on large data sets! Thanks!Pedi

© 2022 - 2024 — McMap. All rights reserved.