Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy mask to count number of elements satisfying a condition

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.

like image 272
Surabhi Amit Chembra Avatar asked Apr 10 '18 20:04

Surabhi Amit Chembra


People also ask

How do you count occurrences of each element in an array in Python?

Method 4: Count occurrences of an element in a list Using countof() Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value.

How do you count elements in Ndarray?

Count the number of elements satisfying the condition for the entire ndarray. The comparison operation of ndarray returns ndarray with bool ( True , False ). Using np. count_nonzero() gives the number of True , i.e., the number of elements that satisfy the condition.

Is there a count function in NumPy?

NumPy: count() function count() function returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. Input an array_like of string or unicode. The substring to search for.


1 Answers

np.count_nonzero should be a bit faster than the sum:

np.count_nonzero(arr1 > 0.6)

In fact, it is three times as fast

>>> from timeit import repeat
>>> kwds = dict(globals=globals(), number=10000)
>>> 
>>> arr1 = np.random.rand(184,184)
>>> 
>>> repeat('np.count_nonzero(arr1 > 0.6)', **kwds)
[0.15281831508036703, 0.1485864429268986, 0.1477385900216177]
>>> repeat('(arr1 > 0.6).sum()', **kwds)
[0.5286932559683919, 0.5260644309455529, 0.5260107989888638]
like image 122
Paul Panzer Avatar answered Oct 18 '22 22:10

Paul Panzer