If I have a given 2d numpy array how can I efficiently make a mask of this array using 0s and 1s depending on where the values of this array are over a given threshold?
So far I made a working code that do this job like this:
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)
I refuse myself to believe that there isn't a smarter way to do it without needing to use two nested FOR loops.
Thanks