如果我有一个给定的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)
我拒绝相信,没有一种更聪明的方法不需要为循环使用两个嵌套的。你知道吗
谢谢
最快的方法是:
示例:
相关问题 更多 >
编程相关推荐