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


使用 **numpy.squeeze()** 方法壓縮陣列的形狀。這會從陣列中移除長度為一的軸。軸透過 "axis" 引數設定。

該函式返回輸入陣列,但已移除所有或一部分長度為 1 的維度。這始終是陣列本身或陣列的檢視。如果所有軸都被壓縮,則結果為一個 0 維陣列,而不是標量。

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

步驟

首先,匯入所需的庫 -

import numpy as np

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

arr = np.array([[[57, 78], [54, 69]]])

顯示陣列 -

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() 方法壓縮陣列的形狀。軸透過 "axis" 引數設定 -

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

示例

import numpy as np

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

# 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 # The axis is set using the "axis" parameter print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).shape)

輸出

Our Array...
[[[57 78]
[54 69]]]

Dimensions of our Array...
3

Datatype of our Array object...
int64

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

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

更新於: 2022年2月18日

126 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.