移除NumPy陣列中長度為一的軸(沿軸0)
使用**numpy.squeeze()**方法壓縮陣列形狀。這將移除陣列中長度為一的軸。軸由“axis”引數設定。這裡我們將axis設定為0。
該函式返回輸入陣列,但移除所有或一部分長度為1的維度。這始終是陣列本身或輸入陣列的檢視。如果所有軸都被壓縮,結果將是一個0維陣列,而不是標量。
axis引數選擇形狀中長度為一的條目子集。如果選擇的軸的形狀條目大於一,則會引發錯誤。
步驟
首先,匯入所需的庫:
import numpy as np
使用array()方法建立一個NumPy陣列。我們添加了整型元素:
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()方法壓縮陣列形狀。軸由“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([[[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
# The axis is set using the "axis" parameter
print("
Squeeze the shape of Array...
",np.squeeze(arr, axis = 0).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)
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP