I have a masked array, from which I'd like to return the index of the minimum value. Further, I'd like to return the index of a randomly chosen minimum if there are multiple. In the example below, this should randomly return
index 4 or 5:
import numpy as np
import numpy.ma as ma
import random
my_mask = [1, 0, 0, 1, 0, 0]
my_array = [ 0.018, 0.011, 0.004, 0.003, 0.0, 0.0]
masked_array = ma.masked_array(my_array,my_mask)
min_indices = np.where(masked_array.min() == masked_array)
min_index = np.random.choice(min_indices[0])
print masked_array
print min_index
My problem: The masked elements are treated as zero (?), and any element from {0,3,4,5} can be returned.
My question: What is a good way to return the index of a (randomly chosen) minimum from an array (excluding masked values)?
Use ma.where() instead of np.where()
min_indices = ma.where(masked_array == masked_array.min()))
print(min_indices)
Which gives:
(array([4, 5]),)
The ma module has a lot of functions that are designed to work with masked arrays.
Finally, grabbing a random element from this result would be something like:
min_index = np.random.choice(min_indices[0])
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