count_nonzero

count_nonzero(x: array, /, *, axis: int | Tuple[int, ...] | None = None, keepdims: bool = False) array

Counts the number of array elements which are non-zero.

Parameters:
  • x (array) – input array.

  • axis (Optional[Union[int, Tuple[int, ...]]]) – axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. Default: None.

  • keepdims (bool) – if True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see Broadcasting). Otherwise, if False, the reduced axes (dimensions) must not be included in the result. Default: False.

Returns:

out (array) – if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array must have the default array index data type.

Notes

  • If x has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.

  • If x has a boolean data type, non-zero elements are those elements which are equal to True.