在 NumPy 中移除長度為一的軸(指定軸)


要移除長度為一的軸,可以使用 NumPy 中的 **ma.MaskedArray.squeeze()** 方法。軸可以透過 "axis" 引數設定。該軸選擇形狀中長度為一的條目子集。如果選擇了一個形狀條目大於一的軸,則會引發錯誤。

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

步驟

首先,匯入所需的庫 -

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立包含整數元素的陣列 -

arr = np.array([[[15], [30], [45]]])
print("Array...
", arr) print("
Array type...
", arr.dtype)

獲取陣列的維度 -

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

建立一個掩碼陣列,並將其中一些標記為無效 -

maskArr = ma.masked_array(arr, mask =[[0, 1, 0]])
print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype)

獲取掩碼陣列的維度 -

print("
Our Masked Array Dimensions...
",maskArr.ndim)

獲取掩碼陣列的形狀 -

print("
Our Masked Array Shape...
",maskArr.shape)

獲取掩碼陣列的元素數量 -

print("
Elements in the Masked Array...
",maskArr.size)

要移除長度為一的軸,可以使用 NumPy 中的 ma.MaskedArray.squeeze() 方法。軸可以透過 "axis" 引數設定 -

print("
Result...
",np.squeeze(maskArr, axis = 0)) print("
Shape...
",np.squeeze(maskArr, axis = 0).shape)

示例

# Python ma.MaskedArray - Remove axes of length one with specific axis

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[[15], [30], [45]]])
print("Array...
", arr) print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[0, 1, 0]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("
Our Masked Array Dimensions...
",maskArr.ndim) # Get the shape of the Masked Array print("
Our Masked Array Shape...
",maskArr.shape) # Get the number of elements of the Masked Array print("
Elements in the Masked Array...
",maskArr.size) # To remove axes of length one, use the ma.MaskedArray.squeeze() method in Numpy # The axis is set using the "axis" parameter print("
Result...
",np.squeeze(maskArr, axis = 0)) print("
Shape...
",np.squeeze(maskArr, axis = 0).shape)

輸出

Array...
[[[15]
[30]
[45]]]

Array type...
int64

Array Dimensions...
3

Our Masked Array
[[[15]
[--]
[45]]]

Our Masked Array type...
int64

Our Masked Array Dimensions...
3

Our Masked Array Shape...
(1, 3, 1)

Elements in the Masked Array...
3

Result...
[[15]
[--]
[45]]
Shape...
(3, 1)

更新於: 2022年2月3日

145 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.