在 NumPy 中,将指定轴向后滚动直至到达给定位置
要将指定的轴向后滚动,直到它位于给定位置,请使用 Python NumPy 中的 numpy.moveaxis() 方法。这里:
- 第一个参数是输入数组。
- 第二个参数是要滚动的轴。其他轴的位置彼此之间不会改变。
- 第三个参数是起始位置,即当 start <= axis 时,轴将向后滚动,直到它位于此位置。
当 start > axis 时,轴将滚动直到它位于此位置之前。
步骤
首先,导入所需的库:
import numpy as np
创建一个包含 1 的数组:
arr = np.ones((2, 3, 4, 5))
显示我们的数组:
print("Array...
",arr)
获取数据类型:
print("
Array datatype...
",arr.dtype)
获取数组的维度:
print("
Array Dimensions...
",arr.ndim)
获取数组的形状:
print("
Our Array Shape...
",arr.shape)
要将指定的轴向后滚动,直到它位于给定位置,请使用 numpy.moveaxis() 方法:
print("
Result
",np.rollaxis(arr, 3, 1).shape) print("
Result
",np.rollaxis(arr, 2).shape) print("
Result
",np.rollaxis(arr, 1).shape) print("
Result
",np.rollaxis(arr, 1, 4).shape)
示例
import numpy as np # Create an array with ones arr = np.ones((2, 3, 4, 5)) # 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 roll the specified axis backwards, until it lies in a given position, use the numpy.moveaxis() method in Python Numpy # Here, the 1st parameter is the Input array # The 2nd parameter is the axis to be rolled. The positions of the other axes do not change relative to one another. # The 3rd parameter is the start i.e. when start <= axis, the axis is rolled back until it lies in this position. # When start > axis, the axis is rolled until it lies before this position. print("
Result
",np.rollaxis(arr, 3, 1).shape) print("
Result
",np.rollaxis(arr, 2).shape) print("
Result
",np.rollaxis(arr, 1).shape) print("
Result
",np.rollaxis(arr, 1, 4).shape)
输出
Array... [[[[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]] [[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]] [[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]]] [[[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]] [[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]] [[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]]]] Array datatype... float64 Array Dimensions... 4 Our Array Shape... (2, 3, 4, 5) Result (2, 5, 3, 4) Result (4, 2, 3, 5) Result (3, 2, 4, 5) Result (2, 4, 5, 3)
广告