Search code examples
pythonnumpydimensions

How to move zero axis to the last position in python?


How to move zero axis to the last position in python?

I tried

a.swapaxis(0,-1)

but it not only put zero axed to the end, but also put last axis to the beginning.

I tried to play with rollaxis but didn't understand what it does.


Solution

  • I think you're looking for moveaxis:

    In [11]: a = np.arange(8).reshape(2, 2, 2)
    
    In [12]: a
    Out[12]:
    array([[[0, 1],
            [2, 3]],
    
           [[4, 5],
            [6, 7]]])
    
    In [13]: a.swapaxes(0, -1)
    Out[13]:
    array([[[0, 4],
            [2, 6]],
    
           [[1, 5],
            [3, 7]]])
    
    In [14]: np.moveaxis(a, 0, -1)
    Out[14]:
    array([[[0, 4],
            [1, 5]],
    
           [[2, 6],
            [3, 7]]])