【发布时间】: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