mindspore.numpy.count_nonzero(x, axis=None, keepdims=False)[source]

Counts the number of non-zero values in the tensor x.

  • x (Tensor) – The tensor for which to count non-zeros.

  • axis (Union[int,tuple], optional) – Axis 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 x.

  • keepdims (bool, optional) – If 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 x.


Tensor, indicating number of non-zero values in the x along a given axis. Otherwise, the total number of non-zero values in x is returned.

  • TypeError – If axis is not int or tuple.

  • ValueError – If axis is not in range [-x.ndim, x.ndim)

Supported Platforms:

Ascend GPU CPU


>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
>>> output = np.count_nonzero(x)
>>> print(output)