bundles / numpy 2.4.4 / numpy / count_nonzero
_ArrayFunctionDispatcher
numpy:count_nonzero
source: /numpy/_core/numeric.py :483
Signature
def count_nonzero ( a , axis = None , * , keepdims = False ) Summary
Counts the number of non-zero values in the array a.
Extended Summary
The word "non-zero" is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object's "truthfulness". For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.
Parameters
a: array_likeThe array for which to count non-zeros.
axis: int or tuple, optionalAxis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of
a.keepdims: bool, optionalIf this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
Returns
count: int or array of intNumber of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.
Examples
import numpy as np np.count_nonzero(np.eye(4)) a = np.array([[0, 1, 7, 0], [3, 0, 2, 19]]) np.count_nonzero(a) np.count_nonzero(a, axis=0) np.count_nonzero(a, axis=1) np.count_nonzero(a, axis=1, keepdims=True)✓
See also
- nonzero
Return the coordinates of all the non-zero values.
Aliases
-
numpy.count_nonzero