在 NumPy 中擴充套件陣列在特定軸上的形狀


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

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日

164 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.