numpy.rollaxis在做什么?

时间:2018-09-25 15:04:27

标签: python numpy

import numpy as np
a=np.arange(8)    
a=a.reshape(2,2,2)
print(a)  

我能理解的答案是:

  [[[0 1]
      [2 3]]
     [[4 5]
      [6 7]]]

但是当print(np.rollaxis(a,2))时,我无法理解答案:

 [[[0 2]
      [4 6]]
     [[1 3]
      [5 7]]]

当打印(np.rollaxis(a,2,1))时,我也无法理解答案:

 [[[0 2]
      [1 3]]
     [[4 6]
      [5 7]]]

这些侧倾轴的过程是什么?

1 个答案:

答案 0 :(得分:1)

通过在每个轴上使用具有相同大小的数组使您感到困难,因此很难看到rollaxis正在执行的转换。沿每个轴大小变化的数组上的此操作更容易理解。


这是一个更好的例子:

a = np.arange(8).reshape(4,2,1)

rollaxis使用您指定的轴,并将其移动到给定位置(默认值为0):

>>> a.shape
(4, 2, 1)
>>> np.rollaxis(a, 1).shape               # Rolls axis 1 to position 0
(2, 4, 1)
>>> np.rollaxis(a, 2).shape               # Rolls axis 2 to position 0
(1, 4, 2)

虽然仍支持此功能,但最佳实践是使用numpy.moveaxis,其行为类似,但没有默认的轴终点参数:

>>> np.moveaxis(a, 2).shape
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-77b5e96d3a20> in <module>()
----> 1 np.moveaxis(a, 2).shape

TypeError: moveaxis() missing 1 required positional argument: 'destination'

>>> np.moveaxis(a, 2, 0).shape
(1, 4, 2)