在NumPy中返回掩碼陣列的掩碼或全為False的布林陣列


要返回掩碼陣列的掩碼或全為False的布林陣列,請在Python NumPy中使用**ma.getmaskarray()**方法。如果arr是MaskedArray且掩碼不是nomask,則返回arr的掩碼作為ndarray;否則,返回與arr形狀相同的全為False的布林陣列。

掩碼陣列是標準numpy.ndarray和掩碼的組合。掩碼可以是nomask(表示關聯陣列中沒有無效值),也可以是布林陣列,用於確定關聯陣列中每個元素的值是否有效。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

使用numpy.arange()方法建立一個包含整型元素的4x4陣列:

arr = np.arange(16).reshape((4,4))
print("Array...
", arr) print("
Array type...
", arr.dtype)

獲取陣列的維度:

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

獲取陣列的形狀:

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

獲取陣列的元素個數:

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

建立一個掩碼陣列:

arr = ma.array(arr)

統計沿特定軸的掩碼元素個數:

print("
The number of masked elements...
",ma.count_masked(arr))

要返回掩碼陣列的掩碼或全為False的布林陣列,請在Python NumPy中使用ma.getmaskarray()方法:

print("
Result (mask of a masked array)...
",ma.getmaskarray(arr))

示例

import numpy as np
import numpy.ma as ma

# Creating a 4x4 array with int elements using the numpy.arange() method
arr = np.arange(16).reshape((4,4))
print("Array...
", arr) print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) print("
Our Array type...
", arr.dtype) # Get the shape of the Array print("
Our Masked Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Masked Array...
",arr.size) # Create a masked array arr = ma.array(arr) # Count the number of masked elements along specific axis print("
The number of masked elements...
",ma.count_masked(arr)) # To return the mask of a masked array, or full boolean array of False, use the ma.getmaskarray() method in Python Numpy print("
Result (mask of a masked array)...
",ma.getmaskarray(arr))

輸出

Array...
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Array type...
int64

Array Dimensions...
2

Our Array type...
int64

Our Masked Array Shape...
(4, 4)

Elements in the Masked Array...
16

The number of masked elements...
0

Result (mask of a masked array)...
[[False False False False]
[False False False False]
[False False False False]
[False False False False]]

更新於:2022年2月21日

348 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告