2

I have a numpy array that I need to change the order of the axis. To do that I am using moveaxis() method, which only returns a view of the input array, by changing only the strides of the array.

However, this does not change the order that the data are stored in the memory. This is problematic for me because I need to pass this reorderd array to a C code in which the order that the data are stored matters.

import numpy as np

a=np.arange(12).reshape((3,4))
a=np.moveaxis(a,1,0)

In this example, a is originally stored continuously in the memory as [0,1,2,...,11]. I would like to have it stored [0,4,8,1,5,9,2,6,10,3,7,11], and obviously moveaxis() did not do the trick

How could I force numpy to rewrite the array in the memory the way I want? I precise that contrary to my simple example, I am manipulating 3D or 4D data, so I cannot simply change the ordering from row to col major when I create it.

Thanks!

2
  • 3
    Simply do np.moveaxis(a,1,0).copy()? That should create a new array with fresh memory allocation. Commented Jan 14, 2021 at 12:02
  • Hi @Ananda, that did the trick, thanks! If you put it as an answer I could validate it. Thanks again! Commented Jan 14, 2021 at 12:56

1 Answer 1

1

The order parameter of the numpy.reshape(...,order='F') function does exactly what you want

a=np.arange(12).reshape((4,3),order='F')
a.flatten()

array([ 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11])

Sign up to request clarification or add additional context in comments.

1 Comment

As I explained in my post, I am working with 3D or 4D array, so this cannot work. But thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.