Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearranging axes in numpy?

Tags:

python

numpy

I have an ndarray such as

>>> arr = np.random.rand(10, 20, 30, 40)
>>> arr.shape
(10, 20, 30, 40)

whose axes I would like to swap around into some arbitrary order such as

>>> rearranged_arr = np.swapaxes(np.swapaxes(arr, 1,3), 0,1)
>>> rearranged_arr.shape
(40, 10, 30, 20)

Is there a function which achieves this without having to chain together a bunch of np.swapaxes?

like image 983
Moormanly Avatar asked Aug 10 '19 00:08

Moormanly


People also ask

How do I flip columns and rows in NumPy?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.

What is transpose in NumPy?

The numpy. transpose() function changes the row elements into column elements and the column elements into row elements. The output of this function is a modified array of the original one.

What is axis =- 1 mean in NumPy?

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.


2 Answers

There are two options: np.moveaxis and np.transpose.

  • np.moveaxis(a, sources, destinations) docs

    This function can be used to rearrange specific dimensions of an array. For example, to move the 4th dimension to be the 1st and the 2nd dimension to be the last:

    >>> rearranged_arr = np.moveaxis(arr, [3, 1], [0, 3])
    >>> rearranged_arr.shape
    (40, 10, 30, 20)
    

    This can be particularly useful if you have many dimensions and only want to rearrange a small number of them. e.g.

    >>> another_arr = np.random.rand(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    >>> np.moveaxis(another_arr, [8, 9], [0, 1]).shape
    (8, 9, 0, 1, 2, 3, 4, 5, 6, 7)
    
  • np.transpose(a, axes=None) docs

    This function can be used to rearrange all dimensions of an array at once. For example, to solve your particular case:

    >>> rearranged_arr = np.transpose(arr, axes=[3, 0, 2, 1])
    >>> rearranged_arr.shape
    (40, 10, 30, 20)
    

    or equivalently

    >>> rearranged_arr = arr.transpose(3, 0, 2, 1)
    >>> rearranged_arr.shape
    (40, 10, 30, 20)
    
like image 82
Moormanly Avatar answered Oct 08 '22 17:10

Moormanly


In [126]: arr = np.random.rand(10, 20, 30, 40)                                                               
In [127]: arr.transpose(3,0,2,1).shape                                                                       
Out[127]: (40, 10, 30, 20)
like image 42
hpaulj Avatar answered Oct 08 '22 19:10

hpaulj