我有一个掩码数组,我想从中返回最小值 的索引。此外,如果有多个,我想返回随机选择的最小值的索引。在下面的例子中,这应该随机返回
索引 4
或 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
我的问题:屏蔽的元素被视为零 (?),可以返回 {0,3,4,5}
中的任何元素。
我的问题:从数组(不包括屏蔽值)返回(随机选择的)最小值的索引的好方法是什么?
最佳答案
使用 ma.where()
而不是 np.where()
min_indices = ma.where(masked_array == masked_array.min()))
print(min_indices)
给出:
(array([4, 5]),)
ma
模块有很多函数是为处理掩码数组而设计的。
最后,从这个结果中获取一个随机元素会是这样的:
min_index = np.random.choice(min_indices[0])
关于python - 获取掩码数组的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32493055/