Rearranging axes in numpy?

拟墨画扇 提交于 2021-02-06 20:01:53

问题


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?


回答1:


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)
    



回答2:


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)


来源:https://stackoverflow.com/questions/57438392/rearranging-axes-in-numpy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!