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


要擴充套件陣列的形狀,可以使用 **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=1)

顯示擴充套件後的陣列:

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=1) # 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...
(6, 1)

Dimensions of our Array...
2

更新於:2022年2月17日

3K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

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