How to count values in a certain range in a Numpy array?
You could use histogram
. Here's a basic usage example:
>>> import numpy
>>> a = numpy.random.random(size=100) * 100
>>> numpy.histogram(a, bins=(0.0, 7.3, 22.4, 55.5, 77, 79, 98, 100))
(array([ 8, 14, 34, 31, 0, 12, 1]),
array([ 0. , 7.3, 22.4, 55.5, 77. , 79. , 98. , 100. ]))
In your particular case, it would look something like this:
>>> numpy.histogram(a, bins=(25, 100))
(array([73]), array([ 25, 100]))
Additionally, when you have a list of strings, you have to explicitly specify the type, so that numpy
knows to produce an array of floats instead of a list of strings.
>>> strings = [str(i) for i in range(10)]
>>> numpy.array(strings)
array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
dtype='|S1')
>>> numpy.array(strings, dtype=float)
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
Building on Sven's good approach, you can also do the slightly more explicit:
numpy.count_nonzero((25 < a) & (a < 100))
This first creates an array of booleans with one boolean for each input number in array a
, and then count the number of non-False (i.e. True) values (which gives the number of matching numbers).
Note, however, that this approach is twice as slow as Sven's .sum()
approach, on an array of 100k numbers (NumPy 1.6.1, Python 2.7.3)–about 300 µs versus 150 µs.
If your array is called a
, the number of elements fulfilling 25 < x < 100
is
((25 < a) & (a < 100)).sum()
The expression (25 < a) & (a < 100)
results in a Boolean array with the same shape as a
with the value True
for all elements that satisfy the condition. Summing over this Boolean array treats True
values as 1
and False
values as 0
.