從 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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP