【问题标题】:Get minimum value of masked array获取掩码数组的最小值
【发布时间】:2015-12-06 05:16:28
【问题描述】:

我有一个掩码数组,我想从中返回最小值索引。此外,如果有多个,我想返回随机选择的最小值的索引。在下面的示例中,这应该随机返回 索引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} 的任何元素。

我的问题:从数组(不包括掩码值)中返回(随机选择的)最小值的索引的好方法是什么?

【问题讨论】:

  • 据我所知,masked_array.min 确实忽略了掩码值。您实际上在数组的有效部分中有零。

标签: python arrays numpy indexing mask


【解决方案1】:

使用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])

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多