How to use Numpy to vectorize this for loop?
count=0
arr1 = np.random.rand(184,184)
for i in range(arr1.size[0]):
for j in range(arr1.size[1]):
if arr1[i,j] > 0.6:
count += 1
print count
I tried:
count=0
arr1 = np.random.rand(184,184)
mask = (arr1>0.6)
indices = np.where(mask)
print indices , len(indices)
I expected len(indices) to give count, but it didn't. Any suggestions please.
You can also use size attribute of Numpy array:
np.count_nonzero
should be a bit faster than the sum:In fact, it is three times as fast
Get a boolean mask and just count the "True"s: