移動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)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP