在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+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告