Counts the number of non-zero values in the array ``a``. A non-zero value is one that evaluates to truthful in a boolean context, including any non-zero number and any string that is not empty. This function recursively counts how many elements in ``a`` (and its sub-arrays) are
(a, axis=None, *, keepdims=False)
| 482 | |
| 483 | @array_function_dispatch(_count_nonzero_dispatcher) |
| 484 | def count_nonzero(a, axis=None, *, keepdims=False): |
| 485 | """ |
| 486 | Counts the number of non-zero values in the array ``a``. |
| 487 | |
| 488 | A non-zero value is one that evaluates to truthful in a boolean |
| 489 | context, including any non-zero number and any string that |
| 490 | is not empty. This function recursively counts how many elements |
| 491 | in ``a`` (and its sub-arrays) are non-zero values. |
| 492 | |
| 493 | Parameters |
| 494 | ---------- |
| 495 | a : array_like |
| 496 | The array for which to count non-zeros. |
| 497 | axis : int or tuple, optional |
| 498 | Axis or tuple of axes along which to count non-zeros. |
| 499 | Default is None, meaning that non-zeros will be counted |
| 500 | along a flattened version of ``a``. |
| 501 | keepdims : bool, optional |
| 502 | If this is set to True, the axes that are counted are left |
| 503 | in the result as dimensions with size one. With this option, |
| 504 | the result will broadcast correctly against the input array. |
| 505 | |
| 506 | Returns |
| 507 | ------- |
| 508 | count : int or array of int |
| 509 | Number of non-zero values in the array along a given axis. |
| 510 | Otherwise, the total number of non-zero values in the array |
| 511 | is returned. |
| 512 | |
| 513 | See Also |
| 514 | -------- |
| 515 | nonzero : Return the coordinates of all the non-zero values. |
| 516 | |
| 517 | Examples |
| 518 | -------- |
| 519 | >>> import numpy as np |
| 520 | >>> np.count_nonzero(np.eye(4)) |
| 521 | np.int64(4) |
| 522 | >>> a = np.array([[0, 1, 7, 0], |
| 523 | ... [3, 0, 2, 19]]) |
| 524 | >>> np.count_nonzero(a) |
| 525 | np.int64(5) |
| 526 | >>> np.count_nonzero(a, axis=0) |
| 527 | array([1, 1, 2, 1]) |
| 528 | >>> np.count_nonzero(a, axis=1) |
| 529 | array([2, 3]) |
| 530 | >>> np.count_nonzero(a, axis=1, keepdims=True) |
| 531 | array([[2], |
| 532 | [3]]) |
| 533 | """ |
| 534 | if axis is None and not keepdims: |
| 535 | return multiarray.count_nonzero(a) |
| 536 | |
| 537 | a = asanyarray(a) |
| 538 | |
| 539 | # TODO: this works around .astype(bool) not working properly (gh-9847) |
| 540 | if np.issubdtype(a.dtype, np.character): |
| 541 | a_bool = a != a.dtype.type() |
no test coverage detected
searching dependent graphs…