從 NumPy 陣列中移除長度為一的軸


使用 Python NumPy 中的 **numpy.squeeze()** 方法壓縮陣列形狀。這將從陣列中移除長度為一的軸。該函式返回輸入陣列,但移除所有或一部分長度為 1 的維度。這始終是陣列本身或輸入陣列的檢視。如果所有軸都被壓縮,則結果為一個 0 維陣列,而不是標量。

軸選擇形狀中長度為一的條目子集。如果選擇的軸的形狀條目大於 1,則會引發錯誤。

步驟

首先,匯入所需的庫 -

import numpy as np

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

arr = np.array([[[20, 36, 57, 78], [32, 54, 69, 84]]])

顯示陣列 -

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

檢查維度 -

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

獲取資料型別 -

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

顯示陣列的形狀 -

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

使用 numpy.squeeze() 方法壓縮陣列形狀 -

print("
Squeeze the shape of Array...
",np.squeeze(arr).shape)

示例

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[[20, 36, 57, 78], [32, 54, 69, 84]]])

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Display the shape of array print("
Array Shape...
",arr.shape) # Squeeze the Array shape using the numpy.squeeze() method print("
Squeeze the shape of Array...
",np.squeeze(arr).shape)

輸出

Our Array...
[[[20 36 57 78]
[32 54 69 84]]]

Dimensions of our Array...
3

Datatype of our Array object...
int64

Array Shape...
(1, 2, 4)

Squeeze the shape of Array...
(2, 4)

更新於: 2022年2月18日

4K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.