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]:
data = np.random.randn(7, 3)
Number of positive values:
[3]:
(data > 0).sum()
[3]:
12
Number of negative values:
[4]:
(data < 0).sum()
[4]:
9
There are two additional methods, any
and all
, which are particularly useful for Boolean arrays:
any
checks whether one or more values in an array are trueall
checks whether each value is true
[5]:
data2 = np.random.randn(7, 3)
bools = data > data2
bools
[5]:
array([[ True, True, True],
[ True, True, False],
[ True, False, False],
[ True, False, True],
[ True, True, False],
[False, False, True],
[False, False, False]])
[6]:
bools.any()
[6]:
True
[7]:
bools.all()
[7]:
False