移动NumPy数组的轴到新的位置


要将数组的轴移动到新的位置,请在Python NumPy中使用**numpy.moveaxis()**方法。这里,第一个参数是要重新排序其轴的数组。第二个参数是源整数或整数序列,即要移动的轴的原始位置。这些必须是唯一的。第三个参数是目标整数或整数序列。每个原始轴的目标位置。这些也必须是唯一的。

步骤

首先,导入所需的库:

import numpy as np

创建一个包含零的数组:

arr = np.zeros((2, 3, 4))

显示我们的数组:

print("Array...
",arr)

获取数据类型:

print("
Array datatype...
",arr.dtype)

获取数组的维度:

print("
Array Dimensions...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

要将数组的轴移动到新的位置,请使用numpy.moveaxis()方法:

print("
Result
",np.moveaxis(arr, 0, -1).shape) print("
Result
",np.moveaxis(arr, -1, 0).shape)

示例

import numpy as np

# Create an array with zeros
arr = np.zeros((2, 3, 4))

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To move axes of an array to new positions, use the numpy.moveaxis() method in Python Numpy # Here, the 1st parameter is the array whose axes should be reordered. # The 2nd parameter is the sourceint or sequence of int i.e. original positions of the axes to move. These must be unique. # The 3rd parameter is the destinationint or sequence of int. The Destination positions for each of the original axes. # These must also be unique. print("
Result
",np.moveaxis(arr, 0, -1).shape) print("
Result
",np.moveaxis(arr, -1, 0).shape) print("
Result
",np.transpose(arr).shape) print("
Result
",np.swapaxes(arr, 0, -1).shape)

输出

Array...
[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]

Array datatype...
float64

Array Dimensions...
3

Our Array Shape...
(2, 3, 4)

Result
(3, 4, 2)

Result
(4, 2, 3)

Result
(4, 3, 2)

Result
(4, 3, 2)

更新于:2022年2月17日

1K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告