NumPy Count True


We have an array containing Boolean elements. The goal is to determine how many of those elements in the array are True.

Solution 1

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.

Solution 2

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)

Example 1

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]
print(“non-zero”, np.count_nonzero(arr))

The code above should determine the number of the non-zero values and print the result as shown:

non-zero 7

Example 2

The same case applies to Boolean values as shown in the array below:

arr = [[True, False, True], [True, False, False]]
print("non-zero", np.count_nonzero(arr))

The output result is as shown:

non-zero 3

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.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list