![]() |
VOOZH | about |
When working with arrays, sometimes you need to quickly count how many elements are not equal to zero. NumPy makes this super easy with the numpy.count_nonzero() function.
This is useful when:
Example: Let’s start with the simplest example to understand how it works.
3
Explanation: array is [0, 1, 0, 2, 3] and non-zero elements are 1, 2, 3 -> total 3 values.
numpy.count_nonzero(arr, axis=None)
Parameters:
Return Value: int (if axis=None) or array of ints (if axis is given). Represents the count of non-zero elements.
Example 1: In this example, we count all non-zero elements in a 2D array.
6
Explanation: There are 6 values that are not zero.
Example 2: Here, we count non-zero elements column-wise using axis=0.
[1 1 2 1 2]
Explanation:
Example 3: This example counts non-zero elements row-wise using axis=1.
[2 3]
Explanation: Row 0 -> 2 non-zeros (3, 4) and Row 1 -> 3 non-zeros (5, 6, 7)