开发者

numpy reverse multidimensional array

What is the simplest way in numpy to reverse the most inner values of an array like this:

array([[[1, 1, 1, 2],
    [2, 2, 2, 3],
开发者_JAVA技巧    [3, 3, 3, 4]],

   [[1, 1, 1, 2],
    [2, 2, 2, 3],
    [3, 3, 3, 4]]])

so that I get the following result:

array([[[2, 1, 1, 1],
    [3, 2, 2, 2],
    [4, 3, 3, 3]],

   [[2, 1, 1, 1],
    [3, 2, 2, 2],
    [4, 3, 3, 3]]])

Thank you very much!


How about:

import numpy as np
a = np.array([[[10, 1, 1, 2],
               [2, 2, 2, 3],
               [3, 3, 3, 4]],
              [[1, 1, 1, 2],
               [2, 2, 2, 3],
               [3, 3, 3, 4]]])

and the reverse along the last dimension is:

b = a[:,:,::-1]

or

b = a[...,::-1]

although I like the later less since the first two dimensions are implicit and it is more difficult to see what is going on.


For each of the inner array you can use fliplr. It flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.

Sample usage:

import numpy as np
initial_array = np.array([[[1, 1, 1, 2],
                          [2, 2, 2, 3],
                          [3, 3, 3, 4]],
                         [[1, 1, 1, 2],
                          [2, 2, 2, 3],
                          [3, 3, 3, 4]]])
index=0
initial_shape = initial_array.shape
reversed=np.empty(shape=initial_shape)
for inner_array in initial_array:
    reversed[index] = np.fliplr(inner_array)
    index += 1

printing reversed

Output:

array([[[2, 1, 1, 1],
        [3, 2, 2, 2],
        [4, 3, 3, 3]],
       [[2, 1, 1, 1],
        [3, 2, 2, 2],
        [4, 3, 3, 3]]])

Make sure your input array for fliplr function must be at least 2-D.

Moreover if you want to flip array in the up/down direction. You can also use flipud

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜