Search code examples
pythonrotationaxis

Rotate 2D axis around the central x axis


I have a simple 2D array:

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

And would like it to be:

array([[ 9,  10,  11,  12],
       [ 5,  6,  7,  8],
       [ 1, 2, 3, 4]])

How could this be done, and then, in general, how could this be done for an [n,m] sort of array?


Solution

  • You can use np.flipud (up/down) or with similar result np.flip on the axis=0:

    import numpy as np
    
    arr = np.array([[ 1,  2,  3,  4],
                    [ 5,  6,  7,  8],
                    [ 9, 10, 11, 12]])
    
    flipud_arr = np.flipud(arr)
    print(flipud_arr)    
    
    flip_arr = np.flip(arr, axis=0)
    print(flip_arr)
    

    Both have the same output:

    array([[ 9, 10, 11, 12],
           [ 5,  6,  7,  8],
           [ 1,  2,  3,  4]])
    

    Both work in general, so also for even rows:

    arr = np.array([[ 1,  2,  3,  4],
                    [ 5,  6,  7,  8],
                    [ 9, 10, 11, 12],
                    [ 3,  0,  8,  1]])
    np.flipud(arr)  # in place = same memory, for copy see 1st code snippet
    

    Output:

    array([[ 3,  0,  8,  1],
           [ 9, 10, 11, 12],
           [ 5,  6,  7,  8],
           [ 1,  2,  3,  4]])