2

I have a 3 dimensional numpy array. The dimension can go up to 128 x 64 x 8192. What I want to do is to change the order in the first dimension by interchanging pairwise.

The only idea I had so far is to create a list of the indices in the correct order.

order    = [1,0,3,2...127,126]
data_new = data[order]

I fear, that this is not very efficient but I have no better idea so far

1
  • So, data[order] works for you, but you think that could be inefficient? Commented Oct 14, 2016 at 11:55

1 Answer 1

5

You could reshape to split the first axis into two axes, such that latter of those axes is of length 2 and then flip the array along that axis with [::-1] and finally reshape back to original shape.

Thus, we would have an implementation like so -

a.reshape(-1,2,*a.shape[1:])[:,::-1].reshape(a.shape)

Sample run -

In [170]: a = np.random.randint(0,9,(6,3))

In [171]: order = [1,0,3,2,5,4]

In [172]: a[order]
Out[172]: 
array([[0, 8, 5],
       [4, 5, 6],
       [0, 0, 2],
       [7, 3, 8],
       [1, 6, 3],
       [2, 4, 4]])

In [173]: a.reshape(-1,2,*a.shape[1:])[:,::-1].reshape(a.shape)
Out[173]: 
array([[0, 8, 5],
       [4, 5, 6],
       [0, 0, 2],
       [7, 3, 8],
       [1, 6, 3],
       [2, 4, 4]])

Alternatively, if you are looking to efficiently create those constantly flipping indices order, we could do something like this -

order = np.arange(data.shape[0]).reshape(-1,2)[:,::-1].ravel()
Sign up to request clarification or add additional context in comments.

Comments

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.