使用 stack() 在軸 1 上連線一系列 NumPy 陣列


要連線一系列陣列,請在 Python NumPy 中使用 **numpy.stack()** 方法。axis 引數指定結果維度中新軸的索引。這裡,我們設定了軸 1。

該函式返回的堆疊陣列比輸入陣列多一個維度。axis 引數指定結果維度中新軸的索引。例如,如果 axis=0,它將是第一個維度,如果 axis=-1,它將是最後一個維度。

如果提供 out 引數,則將其作為放置結果的目標。形狀必須正確,與如果沒有指定 out 引數則 stack 將返回的形狀匹配。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立兩個 NumPy 陣列。我們插入了 int 型別的元素 -

arr1 = np.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

顯示陣列 -

print("Array 1...
", arr1) print("
Array 2...
", arr2)

獲取陣列的型別 -

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

獲取陣列的維度 -

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

獲取陣列的形狀 -

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要連線一系列陣列,請使用 numpy.stack() 方法。axis 引數指定結果維度中新軸的索引。如果 axis=0,它將是第一個維度,如果 axis=-1,它將是最後一個維度 -

print("
Result (stack over axis 1)...
",np.stack((arr1, arr2), axis = 1))

示例

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To join a sequence of arrays, use the numpy.stack() method in Python Numpy # The axis parameter specifies the index of the new axis in the dimensions of the result. # If axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. print("
Result (stack over axis 1)...
",np.stack((arr1, arr2), axis = 1))

輸出

Array 1...
[49 76 61 82 69 29]

Array 2...
[40 60 89 55 32 98]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(6,)

Our Array 2 Shape...
(6,)

Result (stack over axis 1)...
[[49 40]
[76 60]
[61 89]
[82 55]
[69 32]
[29 98]]

更新於: 2022年2月18日

130 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告