python - 获取掩码数组的最小值

标签 python arrays numpy indexing mask

我有一个掩码数组,我想从中返回最小值索引。此外,如果有多个,我想返回随机选择的最小值的索引。在下面的例子中,这应该随机返回 索引 45:

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/

相关文章:

Python。如何根据另一个列表声明一个列表,但要使它们不相互引用?

python - 如何用python将字符串拆分为2?

jquery - 如何在 JQuery 中创建 JSON 数组?

java - java中将二维数组写入文件

python - Web2py - 如何创建弹出窗口?

arrays - 确保相邻位置没有两只猫或狗所需的最少交换次数

python - 有没有办法获取 numpy 数组(Python)每行的前 k 个值?

python - 如何在 OpenCV 中使用 convertScaleAbs() 函数?

python - Pandas HDFStore : Saving and Retrieving a Series with Hierarchical Period Index

python - django.core.exceptions.ImproperlyConfigured : Error loading MySQLdb module: