Efficiently change order of numpy array
<p>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. </p>

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

<pre><code>order    = [1,0,3,2...127,126]
data_new = data[order]
</code></pre>

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

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

<p>Thus, we would have an implementation like so -</p>

<pre><code>a.reshape(-1,2,*a.shape[1:])[:,::-1].reshape(a.shape)
</code></pre>

<p>Sample run -</p>

<pre><code>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]])
</code></pre>

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

<pre><code>order = np.arange(data.shape[0]).reshape(-1,2)[:,::-1].ravel()
</code></pre>

python numpy