使用 Numpy 中的浮點相等進行掩碼


要在 Python Numpy 中使用浮點相等進行掩碼,請使用 numpy.ma.masked_values() 方法。返回一個 MaskedArray,其中 array x 中的資料與 value 大致相等(使用 isclose 確定),將這些資料進行掩碼。masked_values 的預設容差與 isclose 的相同。

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

步驟

首先,匯入所需的庫 −

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立一個包含 int 元素的陣列 −

arr = np.array([[71, 55, 82.8], [82.8, 33, 39], [73, 82.3, 51], [90, 77, 82.8]])
print("Array...
", arr)

獲取陣列的型別 −

print("
Array type...
", arr.dtype)

獲取陣列的維度 −

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

獲取陣列的形狀 −

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

獲取陣列的元素個數 −

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

要在 Python Numpy 中使用浮點相等進行掩碼,請使用 numpy.ma.masked_values() 方法 −

print("
Result...
",np.ma.masked_values(arr, 82.8))

示例

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[71, 55, 82.8], [82.8, 33, 39], [73, 82.3, 51], [90, 77, 82.8]])
print("Array...
", arr) # Get the type pf array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of Elements in the Array...
",arr.size) # To mask using floating point equality, use the numpy.ma.masked_values() method in Python Numpy print("
Result...
",np.ma.masked_values(arr, 82.8))

輸出

Array...
[[71. 55. 82.8]
[82.8 33. 39. ]
[73. 82.3 51. ]
[90. 77. 82.8]]

Array type...
float64

Array Dimensions...
2

Our Array Shape...
(4, 3)

Number of Elements in the Array...
12

Result...
[[71.0 55.0 --]
[-- 33.0 39.0]
[73.0 82.3 51.0]
[90.0 77.0 --]]

更新日期:2022 年 2 月 4 日

369 次瀏覽

開啟你的 職業 生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.