Numpy中关于np.rollaxis和np.swapaxes的理解

本文介绍了numpy库中用于轴操作的`rollaxis`和`swapaxes`函数。`rollaxis`函数用于将数组的指定轴滚动到另一个位置,不改变元素大小,仅改变下标对应关系。`swapaxes`函数则直接交换两个轴的位置。通过实例展示了这两个函数的使用方法和效果,帮助理解轴操作在多维数组中的应用。
numpy.rollaxis(arr, axis, start)
  • arr:数组
  • axis:要滚动的轴,其它轴的相对位置不变
  • start:默认为零,要滚动到目标位置。

举例说明:

>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape       #把数组a的3轴滚动到1轴位置,其他轴相对位置相对不变
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape          #目标位置可以缺省,默认为0,这里的np.rollaxis(a,2)等价于np.rollaxis(a,2,0)
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)

详细一点的例子是:

In:

a = np.arange(12).reshape((3,2,2))

print("原数组:\n")
print(a)
print(np.where(a==9))
print(a.shape)
print()


#将2轴滚动到0轴
print("执行rollaxis函数后:")
b = np.rollaxis(a,2,0)
print(b)
print(np.where(b==9))
print(b.shape)

Out:

原数组:
[[[ 0  1]
  [ 2  3]]
 [[ 4  5]
  [ 6  7]]
 [[ 8  9]
  [10 11]]]
(array([2], dtype=int64), array([0], dtype=int64), array([1], dtype=int64))    #即元素9所在的位置下标为(2,0,1)
原数组形状: (3, 2, 2)


执行rollaxis函数后:
[[[ 0  2]
  [ 4  6]
  [ 8 10]]
 [[ 1  3]
  [ 5  7]
  [ 9 11]]]
(array([1], dtype=int64), array([2], dtype=int64), array([0], dtype=int64))    #轴滚动之后元素9所在的位置下标为(1,2,0)
轴滚动之后的数组形状:  (2, 3, 2)

可以看出,元素的位置变化与轴变化一致。其实简单来说,轴滚动并不改变元素的大小,只是元素的位置下标因为轴的变化而变化了,相当于三维空间中旋转x,y,z轴,原来在(x,y)平面的点现在可能变成在(y,z)平面上的点了,但是大小并没变,只是相对坐标位置变化了而已。

 

numpy.swapaxes(arr, axis1, axis2)
  • arr:输入的数组
  • axis1:对应第一个轴的整数
  • axis2:对应第二个轴的整数

swapaxes函数的功能很简单,作用是直接交换两个轴,请看下面的例子。

>>> a = np.ones((2,3,4,5,6))
>>> np.swapaxes(a, 3, 1).shape
(2, 5, 4, 3, 6)
>>> np.swapaxes(a, 2,0).shape
(4, 3, 2, 5, 6)
>>> np.swapaxes(a, 4, 2).shape
(2, 3, 6, 5, 4)

详细的例子:

In:

a = np.arange(12).reshape((3,2,2))

print("原数组:\n")
print(a)
print(np.where(a==9))
print(a.shape)
print()


#将2轴和0轴直接交换
print("执行swapaxes函数后:")
b = np.swapaxes(a,2,0)
print(b)
print(np.where(b==9))
print(b.shape)

Out:

原数组:
[[[ 0  1]
  [ 2  3]]
 [[ 4  5]
  [ 6  7]]
 [[ 8  9]
  [10 11]]]
(array([2], dtype=int64), array([0], dtype=int64), array([1], dtype=int64))     #元素9所在原始数组中的位置下标为(2,0,1)
原数组形状: (3, 2, 2)
执行rollaxis函数后:
[[[ 0  4  8]
  [ 2  6 10]]
 [[ 1  5  9]
  [ 3  7 11]]]
(array([1], dtype=int64), array([0], dtype=int64), array([2], dtype=int64))     #元素9在新数组中的位置下标为(1,0,2)
新数组形状: (2, 2, 3)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daimashiren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值