numpy reverse multidimensional array

后端 未结 2 2006
忘掉有多难
忘掉有多难 2020-12-01 20:57

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],
    [3, 3, 3, 4]],

   [[1,         


        
相关标签:
2条回答
  • 2020-12-01 21:10

    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.

    0 讨论(0)
  • 2020-12-01 21:11

    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 讨论(0)
提交回复
热议问题