【问题标题】:How to efficiently produce a masked array of 0s and 1s from a 2d numpy array? [duplicate]如何有效地从 2d numpy 数组中生成 0 和 1 的掩码数组? [复制]
【发布时间】:2018-12-07 16:24:05
【问题描述】:

如果我有一个给定的 2d numpy 数组,如何根据该数组的值超过给定阈值的位置使用 0 和 1 有效地制作该数组的掩码?

到目前为止,我编写了一个可以像这样完成这项工作的工作代码:

import numpy as np

def maskedarray(data, threshold):

    #creating an array of zeros:
    zeros = np.zeros((np.shape(data)[0], np.shape(data)[1]))

    #going over each index of the data
    for i in range(np.shape(data)[0]):
        for j in range(np.shape(data)[1]):
            if data[i][j] > threshold:
                zeros[i][j] = 1

    return(zeros)

#creating a test array
test = np.random.rand(5,5)

#using the function above defined
mask = maskedarray(test,0.5)

我拒绝让自己相信,无需使用两个嵌套的 FOR 循环就没有比这更聪明的方法了。

谢谢

【问题讨论】:

  • numpy.where(condition).astype(np.bool)
  • 对不起,我的意思是np.int

标签: python arrays python-3.x numpy


【解决方案1】:

最快的方法就是:

def masked_array(data, threshold):
    return (data > threshold).astype(int)

例子:

data = np.random.random((5,5))
threshold = 0.5

>>> data
array([[0.42966975, 0.94785801, 0.31750045, 0.75944551, 0.05430315],
       [0.91475934, 0.65683185, 0.09019139, 0.85717157, 0.63074349],
       [0.33160746, 0.82455941, 0.50801804, 0.81087228, 0.01561161],
       [0.6932717 , 0.12741425, 0.17863726, 0.36682108, 0.95817187],
       [0.88320599, 0.51243802, 0.90219452, 0.78954102, 0.96708252]])    

>>> masked_array(data, threshold)
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 1, 1],
       [0, 1, 1, 1, 0],
       [1, 0, 0, 0, 1],
       [1, 1, 1, 1, 1]])

【讨论】:

  • 这个方法也可以用来在值之间进行过滤吗?就像我们希望在您的示例中在 0.3 和 0.5 之间过滤值一样?
  • 是的:((data > 0.3) & (data < 0.5)).astype(int) 创建你的面具,data[mask] 过滤它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多