Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get minimum value of masked array

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)?

like image 496
anon01 Avatar asked Feb 16 '26 20:02

anon01


1 Answers

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])
like image 129
derricw Avatar answered Feb 19 '26 08:02

derricw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!