Methods for Boolean arrays¶
Boolean values have been converted to 1 (True) and 0 (False) in the previous methods. Therefore, sum is often used to count the True values in a Boolean array:
[1]:
import numpy as np
[2]:
rng = np.random.default_rng()
data = rng.normal(size=(7, 3))
Number of positive values:
[3]:
(data >= 0).sum()
[3]:
np.int64(12)
Number of negative values:
[4]:
(data < 0).sum()
[4]:
np.int64(9)
There are two additional methods, any and all, which are particularly useful for Boolean arrays:
anychecks whether one or more values in an array are trueallchecks whether each value is true
[5]:
data2 = rng.normal(size=(7, 3))
bools = data > data2
bools
[5]:
array([[False, False, False],
[False, True, True],
[False, False, False],
[False, True, False],
[False, True, False],
[ True, True, True],
[ True, True, True]])
[6]:
bools.any()
[6]:
np.True_
[7]:
bools.all()
[7]:
np.False_