Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy find number of occurrences in a 2D array

Tags:

python

numpy

Is there a numpy function to count the number of occurrences of a certain value in a 2D numpy array. E.g.

np.random.random((3,3))

array([[ 0.68878371,  0.2511641 ,  0.05677177],
       [ 0.97784099,  0.96051717,  0.83723156],
       [ 0.49460617,  0.24623311,  0.86396798]])

How do I find the number of times 0.83723156 occurs in this array?

like image 909
user308827 Avatar asked Jan 05 '23 18:01

user308827


1 Answers

arr = np.random.random((3,3))
# find the number of elements that get really close to 1.0
condition = arr == 0.83723156
# count the elements
np.count_nonzero(condition)

The value of condition is a list of booleans representing whether each element of the array satisfied the condition. np.count_nonzero counts how many nonzero elements are in the array. In the case of booleans it counts the number of elements with a True value.

To be able to deal with floating point accuracy, you could do something like this instead:

condition = np.fabs(arr - 0.83723156) < 0.001
like image 54
Ritwik Bose Avatar answered Jan 20 '23 12:01

Ritwik Bose