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. A valid axis must be an integer on the interval [-N, N), where N is the number of axes in x. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where -1 refers to the last axis). If provided an invalid axis, the function must raise an exception. Default: None.

  • keepdims (bool) – if True, the reduced axes must be included in the result as singleton dimensions, and, accordingly, the result must be broadcast-compatible with the input array (see Broadcasting). Otherwise, if False, the reduced axes 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.

New in version 2024.12.