user308827 - 3 months ago 52x
Python Question

# Numpy find number of occurrences in a 2D array

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?

To count the number of times `x` appears in any array, you can simply sum the boolean array that results from `a == x`:

``````>>> col = numpy.arange(3)
>>> cols = numpy.tile(col, 3)
>>> (cols == 1).sum()
3
``````

It should go without saying, but I'll say it anyway: this is not very useful with floating point numbers unless you specify a range, like so:

``````>>> a = numpy.random.random((3, 3))
>>> ((a > 0.5) & (a < 0.75)).sum()
2
``````

This general principle works for all sorts of tests. For example, if you want to count the number of floating point values that are integral:

``````>>> a = numpy.random.random((3, 3)) * 10
>>> a
array([[ 7.33955747,  0.89195947,  4.70725211],
[ 6.63686955,  5.98693505,  4.47567936],
[ 1.36965745,  5.01869306,  5.89245242]])
>>> a.astype(int)
array([[7, 0, 4],
[6, 5, 4],
[1, 5, 5]])
>>> (a == a.astype(int)).sum()
0
>>> a[1, 1] = 8
>>> (a == a.astype(int)).sum()
1
``````