How do I test if every element in a numpy array is masked? Here's what I'd like to do:
x = #is a maksed numpy array
masked_min = numpy.ma.min(x)
if masked_min IS NOT A MASKED ELEMENT:
#do some stuff only if masked_min is a value
In practice I see this:
>>> x = numpy.ma.array(numpy.array([1,2,3]),mask=[True,True,True])
>>> masked_min = numpy.ma.min(x)
masked
Testing for masked
is not helpful:
>>> numpy.ma.sum(x) == numpy.ma.masked
masked
To determine whether input has masked values, use the ma. is_masked() method in Python Numpy. Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values. Returns True if the array is a MaskedArray with masked values, False otherwise.
allequal() method in Python Numpy. Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. The fill_value sets whether masked values in a or b are considered equal (True) or not (False).
A masked array is the combination of a standard numpy. ndarray and a mask. A mask is either nomask , indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.
all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.
If by "test if an entire array is masked in numpy" you mean whether every element is masked, since the mask itself an array, you could use .mask.all()
:
>>> x = numpy.ma.array(numpy.array([1,2,3]),mask=[True,True,True])
>>> x
masked_array(data = [-- -- --],
mask = [ True True True],
fill_value = 999999)
>>> x.mask
array([ True, True, True], dtype=bool)
>>> x.mask.all()
True
or maybe .count()
, but that's axis-dependent. OTOH if you really only need to test whether the result of your min call is "masked", you can do that directly:
>>> numpy.ma.min(x)
masked
>>> type(_)
<class 'numpy.ma.core.MaskedConstant'>
>>> isinstance(numpy.ma.min(x), numpy.ma.core.MaskedConstant)
True
>>> numpy.ma.min(x) is numpy.ma.masked
True
[There might be easier ways to do this; I seldom use masked arrays myself.]
I think the most Pythonic way would be to just do what you want, and then catch any errors that result if the entire array is masked.
For example:
x = numpy.ma.array(numpy.array([1,2,3]),mask=[True,True,True])
try:
my_min = numpy.min(x[~x.mask])
# Continue with my_min
except ValueError:
# Bail or what have you
print 'Masks all around!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With