HWilmer
HWilmer

Reputation: 566

Count all values of an array that are between 0 and 1

Is there an effective way to count all the values in a numpy array which are between 0 and 1?

I know this is easily countable with a for loop, but that seems pretty inefficient to me. I tried to play around with the count_nonzero() function but I couldn't make it work the way I wanted.

Greetings

Upvotes: 0

Views: 112

Answers (2)

s3dev
s3dev

Reputation: 9721

One quick and easy method is to use the logical_and() function, which returns a boolean mask array. Then simply use the .sum() function to sum the True values.

Example:

import numpy as np

a = np.array([0, .1, .2, .3, 1, 2])

np.logical_and(a>0, a<1).sum()

Output:

>>> 3

Example 2:

Or, if you'd prefer a more 'low-level' (non-helper function) approach, the & logical operator can be used:

((a > 0) & (a < 1)).sum()

Upvotes: 3

swag2198
swag2198

Reputation: 2696

This might be one way. You can easily replace <= and >= with strict inequalities as per your wish.

>>> import numpy as np
>>> a = np.random.randn(3,3)
>>> a
array([[-2.17470114,  0.59575531,  0.06795138],
       [-0.57380035,  0.05663369,  1.12636801],
       [ 0.55363332, -0.04039947,  1.14837819]])
>>> inds1 = a >= 0
>>> inds2 = a <= 1
>>> inds = inds1 * inds2
>>> inds
array([[False,  True,  True],
       [False,  True, False],
       [ True, False, False]])
>>> inds.sum()
4

Upvotes: 2

Related Questions