在许多情况下,数据集可能不完整或被无效数据污染。例如,传感器可能无法记录数据或记录了无效值。的numpy.ma
模块通过引入掩码数组提供了解决此问题的便捷方法。掩码数组是可能缺少条目或无效条目的数组。
numpy.MaskedArray.masked_where()函数用于屏蔽满足条件的数组,它返回arr作为条件为True时被屏蔽的数组。任何arr或condition的掩码值也将在输出中被掩码。
用法: numpy.ma.masked_where(condition, arr, copy=True)
参数:
condition :[数组]屏蔽条件。当条件测试浮点值是否相等时,请考虑改用masked_values。
arr :[ndarray]我们要屏蔽的输入数组。
copy :[bool]如果为True(默认),则在结果中复制arr。如果为False,则修改arr并返回视图。
Return :[MaskedArray]对条件为True的arr进行掩码的结果。
代码1:
# Python program explaining
# numpy.MaskedArray.masked_where() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([1, 2, 3, -1, 2])
print ("Input array:", in_arr)
# applying MaskedArray.masked_where methods
# to input array where value<= 1
mask_arr = ma.masked_where(in_arr<= 1, in_arr)
print ("Masked array:", mask_arr)
输出:
Input array: [ 1 2 3 -1 2] Masked array: [-- 2 3 -- 2]
代码2:
# Python program explaining
# numpy.MaskedArray.masked_where() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array in_arr1
in_arr1 = geek.arange(4)
print ("1st Input array:", in_arr1)
# applying MaskedArray.masked_where methods
# to input array in_arr1 where value = 1
mask_arr1 = ma.masked_where(in_arr1 == 1, in_arr1)
print ("1st Masked array:", mask_arr1)
# creating input array in_arr2
in_arr2 = geek.arange(4)
print ("2nd Input array:", in_arr2)
# applying MaskedArray.masked_where methods
# to input array in_arr2 where value = 1
mask_arr2 = ma.masked_where(in_arr2 == 3, in_arr2)
print ("2nd Masked array:", mask_arr2)
# applying MaskedArray.masked_where methods
# to 1st masked array where second masked array
# is used as condition
res_arr = ma.masked_where(mask_arr1 == 3, mask_arr2)
print("Resultant Masked array:", res_arr)
输出:
1st Input array: [0 1 2 3] 1st Masked array: [0 -- 2 3] 2nd Input array: [0 1 2 3] 2nd Masked array: [0 1 2 --] Resultant Masked array: [0 -- 2 --]
相关用法
- Python numpy.cov()用法及代码示例
- Python Numpy recarray.put()用法及代码示例
- Python Numpy recarray.ptp()用法及代码示例
- Python numpy.issubsctype()用法及代码示例
- Python Numpy MaskedArray.std()用法及代码示例
- Python Numpy MaskedArray.var()用法及代码示例
- Python numpy.issubdtype()用法及代码示例
- Python Numpy recarray.any()用法及代码示例
- Python Numpy recarray.all()用法及代码示例
- Python numpy.nanmean()用法及代码示例
- Python Numpy recarray.var()用法及代码示例
- Python Numpy MaskedArray.sum()用法及代码示例
- Python Numpy recarray.dot()用法及代码示例
注:本文由纯净天空筛选整理自jana_sayantan大神的英文原创作品 Numpy MaskedArray.masked_where() function | Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。