在NumPy中掩蓋包含無效值(NaN或inf)的陣列元素


要掩蓋出現無效值(NaN或inf)的陣列,請在Python NumPy中使用**numpy.ma.masked_invalid()**方法。此函式是masked_where的快捷方式,條件為=~(np.isfinite(a))。任何預先存在的掩碼都將被保留。僅適用於具有NaN或inf有意義的資料型別的陣列(即浮點型別),但接受任何類陣列物件。

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

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

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

arr = np.array([91.6, 73.8, 29.2, 49.9, 39.7, 73.5, 87.6, 51.1])
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)

為陣列值設定NaN或inf:

arr[1] = np.NaN
arr[3] = np.PINF
arr[6] = np.NaN
arr[7] = np.PINF
print("
Display the updated array...
",arr)

要掩蓋出現無效值(NaN或inf)的陣列,請使用numpy.ma.masked_invalid()方法。在這裡,我們將設定區間,即掩蓋55到90之間的值:

print("
Result...
",ma.masked_invalid(arr))

示例

import numpy as np
import numpy.ma as ma

# Create an array with float elements using the numpy.array() method
arr = np.array([91.6, 73.8, 29.2, 49.9, 39.7, 73.5, 87.6, 51.1])
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) # Set NaNs or infs for array values arr[1] = np.NaN arr[3] = np.PINF arr[6] = np.NaN arr[7] = np.PINF print("
Display the updated array...
",arr) # To mask an array where invalid values occur (NaNs or infs), use the numpy.ma.masked_invalid() method in Python Numpy # Here, we will set the interval i.e. to mask between 55 and 90 print("
Result...
",ma.masked_invalid(arr))

輸出

Array...
[91.6 73.8 29.2 49.9 39.7 73.5 87.6 51.1]

Array type...
float64

Array Dimensions...
1

Our Array Shape...
(8,)

Number of Elements in the Array...
8

Display the updated array...
[91.6 nan 29.2 inf 39.7 73.5 nan inf]

Result...
[91.6 -- 29.2 -- 39.7 73.5 -- --]

更新於:2022年2月4日

2K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.