arraysnumpy

An unusual resorting of a 3d numpy array


Consider the 3d numpy array arr:

[[[ 0,  9,  0,  2], [ 6,  8,  0,  2]],
 [[ 0,  9,  1,  5], [ 4,  8,  1,  5]],
 [[ 1,  0,  1,  2], [ 6,  6,  1,  2]],
 [[ 0,  9,  1,  5], [ 5,  5,  1,  5]],
 [[ 0,  9,  1,  5], [ 6,  5,  1,  5]],
 [[ 1,  0,  1,  2], [ 4,  7,  1,  2]],  
 [[ 0,  9,  3,  4], [ 6,  4,  3,  4]]])

I want to create a new array, new_arr, of the same shape by resorting arr as follows:

Sort by arr[:, 0, 0], then arr[:, 1, 0], then arr[:, 0, 1], then arr[:, 1, 1], etc.

The 2d arrays themselves are unchanged, but they are presented in a different (lexicographic) order within the 3d array.

The desired result is:

new_arr =  np.array(
[[[ 0,  9,  1,  5], [ 4,  8,  1,  5]],
 [[ 0,  9,  1,  5], [ 5,  5,  1,  5]],
 [[ 0,  9,  3,  4], [ 6,  4,  3,  4]],
 [[ 0,  9,  1,  5], [ 6,  5,  1,  5]],
 [[ 0,  9,  0,  2], [ 6,  8,  0,  2]], 
 [[ 1,  0,  1,  2], [ 4,  7,  1,  2]], 
 [[ 1,  0,  1,  2], [ 6,  6,  1,  2]]])

Solution

  • You can do it like this:

    import numpy as np
    arr=np.array([[[ 0,  9,  0,  2], [ 6,  8,  0,  2]],
     [[ 0,  9,  1,  5], [ 4,  8,  1,  5]],
     [[ 1,  0,  1,  2], [ 6,  6,  1,  2]],
     [[ 0,  9,  1,  5], [ 5,  5,  1,  5]],
     [[ 0,  9,  1,  5], [ 6,  5,  1,  5]],
     [[ 1,  0,  1,  2], [ 4,  7,  1,  2]],  
     [[ 0,  9,  3,  4], [ 6,  4,  3,  4]]])
    new_arr=list(arr)
    new_arr.sort(key=lambda x:[x[0][0],x[1][0],x[0][1],x[1][1]])
    new_arr=np.array(new_arr)
    print(new_arr)