NumPy | count_nonzero method
Start your free 7-days trial now!
count_nonzero(~) method counts the number of non-zeros in an array along a given axis.
The array on which to perform the method.
The axis along which we count the number of non-zeros. By default,
Numpy array indicating the number of non-zeros in the input array along the given axis.
Counting non-zeros row-wise
To count the number of non-zeros row-wise in a 2D Numpy array, use the following:
np.count_nonzero([[1,0,1],[0,1,0]], axis=1)array([2, 1])
We get this result because we have 2 non-zeros in the first row, and 1 non-zero in the second row.
Counting non-zeros column-wise
To count the number of non-zeros column-wise in a 2D Numpy array, use the following:
np.count_nonzero([[1,0,1],[0,1,0]], axis=0)array([1, 1, 1])
We get this result because every column contains exactly 1 non-zero value.