We have an array containing Boolean elements. The goal is to determine how many of those elements in the array are True.
The naïve approach would create a sum counter and a for loop that iterates over each element in the array. We then check if that element is true and if yes, we add it to the counter.
After completion, we get the sum variable’s value, the number of True elements in the array.
We can intelligently approach the problem since we are not looking at the naïve approach.
We know that Python treats a False value as 0 and any other value as True. So if that’s the case, we can use the NumPy count_nonzero() function to solve the problem.
The NumPy count_nonzero() function allows us to calculate all the non-zero values in a given array. Or, shall I say, it will enable us to count the number of True values in an array.
The function syntax is as shown:
numpy.count_nonzero(a, axis=None, *, keepdims=False)
Consider the example below that uses the count_nonzero() function to determine the number of non-zero elements in the array.
arr = [1,2,0,3,4,0,5,6,7]
The code above should determine the number of the non-zero values and print the result as shown:
The same case applies to Boolean values as shown in the array below:
arr = [[True, False, True], [True, False, False]]
The output result is as shown:
And with that, we have solved our initial problem.
Thanks for following along with this tutorial where we covered how to use the count_nonzero() function to determine the number of True elements in an array.