Counts the number of non-zero values in the array ``a``. 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
(a, axis=None, *, keepdims=False)
| 414 | |
| 415 | @array_function_dispatch(_count_nonzero_dispatcher) |
| 416 | def count_nonzero(a, axis=None, *, keepdims=False): |
| 417 | """ |
| 418 | Counts the number of non-zero values in the array ``a``. |
| 419 | |
| 420 | The word "non-zero" is in reference to the Python 2.x |
| 421 | built-in method ``__nonzero__()`` (renamed ``__bool__()`` |
| 422 | in Python 3.x) of Python objects that tests an object's |
| 423 | "truthfulness". For example, any number is considered |
| 424 | truthful if it is nonzero, whereas any string is considered |
| 425 | truthful if it is not the empty string. Thus, this function |
| 426 | (recursively) counts how many elements in ``a`` (and in |
| 427 | sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()`` |
| 428 | method evaluated to ``True``. |
| 429 | |
| 430 | Parameters |
| 431 | ---------- |
| 432 | a : array_like |
| 433 | The array for which to count non-zeros. |
| 434 | axis : int or tuple, optional |
| 435 | Axis or tuple of axes along which to count non-zeros. |
| 436 | Default is None, meaning that non-zeros will be counted |
| 437 | along a flattened version of ``a``. |
| 438 | |
| 439 | .. versionadded:: 1.12.0 |
| 440 | |
| 441 | keepdims : bool, optional |
| 442 | If this is set to True, the axes that are counted are left |
| 443 | in the result as dimensions with size one. With this option, |
| 444 | the result will broadcast correctly against the input array. |
| 445 | |
| 446 | .. versionadded:: 1.19.0 |
| 447 | |
| 448 | Returns |
| 449 | ------- |
| 450 | count : int or array of int |
| 451 | Number of non-zero values in the array along a given axis. |
| 452 | Otherwise, the total number of non-zero values in the array |
| 453 | is returned. |
| 454 | |
| 455 | See Also |
| 456 | -------- |
| 457 | nonzero : Return the coordinates of all the non-zero values. |
| 458 | |
| 459 | Examples |
| 460 | -------- |
| 461 | >>> np.count_nonzero(np.eye(4)) |
| 462 | 4 |
| 463 | >>> a = np.array([[0, 1, 7, 0], |
| 464 | ... [3, 0, 2, 19]]) |
| 465 | >>> np.count_nonzero(a) |
| 466 | 5 |
| 467 | >>> np.count_nonzero(a, axis=0) |
| 468 | array([1, 1, 2, 1]) |
| 469 | >>> np.count_nonzero(a, axis=1) |
| 470 | array([2, 3]) |
| 471 | >>> np.count_nonzero(a, axis=1, keepdims=True) |
| 472 | array([[2], |
| 473 | [3]]) |
no test coverage detected