Numpy moveaxis() 函数
Numpy moveaxis() 函数用于将数组中指定的轴移动到新位置,同时保持其余轴的顺序不变。该函数定义在 numpy 模块中,常用于重塑多维数组中的数据,尤其是在需要对轴进行操作的复杂运算中。
在 NumPy 中,numpy.moveaxis() 和 numpy.swapaxes() 均用于重新排列多维数组的轴。主要区别在于 numpy.moveaxis() 允许同时将多个轴移动到不同的指定位置,而 numpy.swapaxes() 每次只能交换两个轴。
numpy.moveaxis() 函数比 numpy.swapaxes() 更灵活,允许同时将多个轴移动到不同的位置。
语法
以下是 Numpy moveaxis() 函数的语法 -
numpy.moveaxis(array, source, destination)
参数
以下是 Numpy moveaxis() 函数的参数 -
- array - 需要移动坐标轴的输入数组。
- source - 一个整数或整数序列,指定要移动坐标轴的原始位置。
- destination - 一个整数或整数序列,指定指定坐标轴的目标位置。
返回值
该函数返回原始数组的视图,其中指定轴已移动到目标位置。
示例
以下是使用 Numpy moveaxis() 函数将二维数组中的轴 0 移动到轴 1 的基本示例 -
import numpy as np my_Array = np.array([[85, 256, 16], [91, 36, 24]]) Moved_Array = np.moveaxis(my_Array, 0, 1) print("原始数组: ", my_Array) print("移动后的轴数组(0 到 1): ", Moved_Array)
输出
原始数组: [[10 20 30] [40 50 60]] 移动后的轴数组(0 到 1): [[10 40] [20 50] [30 60]]
示例 - 移动三维数组中的轴
在以下示例中,我们使用 numpy.moveaxis() 函数将三维 NumPy 数组中的轴 0 移动到轴 2 -
import numpy as np my_Array = np.array([[[71, 44], [25, 100]], [[165, 32], [12, 1]]]) Moved_Array = np.moveaxis(my_Array, 0, 2) print("原始数组: ", my_Array) print("移动后的轴数组(0 到 2): ", Moved_Array)
输出
原始数组: [[[1 2] [3 4]] [[5 6] [7 8]]] 移动后的轴数组(0 到 2): [[[1 5] [2 6]] [[3 7] [4 8]]]
示例 - 在四维数组中移动多个轴
在下面的示例中,我们使用 numpy.moveaxis() 函数移动了四维数组中的多个轴 -
import numpy as np my_Array = np.array([[[[45, 78], [12, 63]], [[76, 82], [69, 56]]], [[[12, 24], [1, 39]], [[59, 85], [105, 43]]]]) Moved_Arr = np.moveaxis(my_Array, [1, 2], [2, 0]) print("原始数组: ", my_Array) print("移动后的轴数组(1 和 2 变为 2 和 0): ", Moved_Arr)
输出
以下是上述代码的输出 -
原始数组: [[[[ 45 78] [ 12 63]] [[ 76 82] [ 69 56]]] [[[ 12 24] [ 1 39]] [[ 59 85] [105 43]]]] 已移动轴数组(1 和 2 变为 2 和 0): [[[[ 45 78] [ 76 82]] [[ 12 24] [ 59 85]]] [[[ 12 63] [ 69 56]] [[ 1 39] [105 43]]]]