在NumPy中擴充套件陣列沿軸0的形狀


要擴充套件陣列的形狀,請使用 **numpy.expand_dims()** 方法。插入一個新軸,它將出現在擴充套件陣列形狀的軸位置。這裡我們將設定軸0。該函式返回維度增加的輸入陣列的檢視。

NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援廣泛的硬體和計算平臺,並且與分散式、GPU 和稀疏陣列庫配合良好。

步驟

首先,匯入所需的庫:

import numpy as np

使用 array() 方法建立陣列:

arr = np.array([5, 10, 15, 20, 25, 30])

顯示陣列:

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

顯示陣列的形狀:

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

檢查維度:

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

獲取資料型別:

print("
Datatype of our Array object...
",arr.dtype)

獲取陣列中元素的數量:

print("
Size of array...
",arr.size)

要擴充套件陣列的形狀,請使用 numpy.expand_dims() 方法:

res = np.expand_dims(arr, axis=0)

顯示擴充套件後的陣列:

print("
Resultant expanded array....
", res)

顯示擴充套件後陣列的形狀:

print("
Shape of the expanded array...
",res.shape)

檢查維度

print("
Dimensions of our Array...
",res.ndim)

示例

import numpy as np

# Creating an array using the array() method
arr = np.array([5, 10, 15, 20, 25, 30])

# Display the array
print("Our Array...
",arr) # Display the shape of array print("
Array Shape...
",arr.shape) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Get the number of elements in an array print("
Size of array...
",arr.size) # To expand the shape of an array, use the numpy.expand_dims() method # Insert a new axis that will appear at the axis position in the expanded array shape. res = np.expand_dims(arr, axis=0) # Display the expanded array print("
Resultant expanded array....
", res) # Display the shape of the expanded array print("
Shape of the expanded array...
",res.shape) # Check the Dimensions print("
Dimensions of our Array...
",res.ndim)

輸出

Our Array...
[ 5 10 15 20 25 30]

Array Shape...
(6,)

Dimensions of our Array...
1

Datatype of our Array object...
int64

Size of array...
6

Resultant expanded array....
[[ 5 10 15 20 25 30]]

Shape of the expanded array...
(1, 6)

Dimensions of our Array...
2

更新於:2022年2月17日

224 次檢視

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.