Reversing the order of a nested array in a 3D matrix

Viewed 55

I have a 3D matrix, or rather, an array of a 2D matrix, and I would like to reverse the order of the deepest dataset.

So say I have:

array([[[ 1      ,  2      ,  3      , ...,
          7      ,  8      ,  9      ],
        ...,
        [ 10      ,  11      ,  12      , ...,
          16      ,  17      ,  18      ]],

       [[ 19      ,  20      ,  21      , ...,
          25      ,  26      ,  27      ],
        ...,
        [ 28      ,  29      ,  30      , ...,
          34      ,  35      ,  36      ]]])

I would want it to be

array([[[ 9      ,  8      ,  7      , ...,
          3      ,  2      ,  1      ],
        ...,
        [ 18      ,  17      ,  16      , ...,
          12      ,  11      ,  10      ]],

       [[ 27      ,  26      ,  25      , ...,
          21      ,  20      ,  19      ],
        ...,
        [ 36      ,  35      ,  34      , ...,
          30      ,  29      ,  28      ]]])

I am currently achieving this result by using the following:

reordered_list = []
for i in range(ts):
    inner_list = []
    for j in range(M_y):
        inner_list.append(original_array[i][j][::-1])
    reordered_list.append(inner_list)

reordered_array = np.array(reordered_list)

but wondered if there was a more efficient route to follow.

Thanks in advance.

2 Answers

you can use:

a = np.array([[[ 1      ,  2      ,  3,   
                  7      ,  8      ,  9      ],

                [ 10      ,  11      ,  12      , 
                  16      ,  17      ,  18      ]],

               [[ 19      ,  20      ,  21      ,
                  25      ,  26      ,  27      ],

                [ 28      ,  29      ,  30      , 
                  34      ,  35      ,  36      ]]])
a[:,:,::-1]

output:

array([[[ 9,  8,  7,  3,  2,  1],
    [18, 17, 16, 12, 11, 10]],

   [[27, 26, 25, 21, 20, 19],
    [36, 35, 34, 30, 29, 28]]]) 

You can use numpy.flip() with the concerned axis (2 here)

    y = np.flip(x, axis=2)
Related