Reputation: 11181
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)?
Upvotes: 3
Views: 3560
Reputation: 7036
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])
Upvotes: 2