关于numpy.rollaxis函数

numpy.rollaxis

numpy.rollaxis 函数向后滚动特定的轴到一个特定位置,格式如下:

numpy.rollaxis(arr, axis, start)参数说明:

  • arr:数组
  • axis:要向后滚动的轴,其它轴的相对位置不会改变
  • start:默认为零,表示完整的滚动。会滚动到特定位置。

import numpy as np

# 创建了三维的 ndarray

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

print ('原数组:')

print (a)

print ('\n')

# 将轴 2 滚动到轴 0(宽度到深度)

print ('调用 rollaxis 函数:')

print (np.rollaxis(a,2))

# 将轴 0 滚动到轴 1:(宽度到高度)

print ('\n')

print ('调用 rollaxis 函数:')

print (np.rollaxis(a,2,1))

输出结果如下:

原数组:

[[[0 1]

[2 3]]

[[4 5]

[6 7]]]

调用 rollaxis 函数:

[[[0 2]

[4 6]]

[[1 3]

[5 7]]]

调用 rollaxis 函数:

[[[0 2]

[1 3]]

[[4 6]

[5 7]]]

[Finished in 0.3s]

分析:

创建的2x2x2是一个三维数组:[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

如果要取数值 2,则a[0][1][0] ,数组下标与值对应如下表:

0(000) 1(001)
2(010) 3(011)
4(100) 5(101)
6(110) 7(111)

程序运行np.rollaxis(a, 2)时,将轴2滚动到了轴0前面,即:5(101) ->6(110), 其他轴相对2轴位置不变(start默认0),数组下标排序由0,1,2变成了1,2,0

这时数组按下标顺序重组,例如第一个数组中[0,1]下标为[000,001],其中0的下标变动不影响值,1位置的下标由001变成010,第一位的下标滚动到最后一位下标的后面,值由1(001)变成2(010):

0(000) ->0(000) 1(001) ->2(010)
2(010) ->4(100) 3(011) ->6(110)
4(100) ->1(001) 5(101) ->3(011)
6(110) ->5(101) 7(111) ->7(111)

猜你喜欢

转载自blog.csdn.net/c710473510/article/details/89452058
今日推荐