10000 `count_nonzero` can return either a builtin `int` or numpy's `intp` · Issue #17562 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content
count_nonzero can return either a builtin int or numpy's intp #17562
Open
@BvB93

Description

@BvB93

The return type of np.count_nonzero() is currently somewhat inconsistent:

  • A builtin integer is returned if axis is None and not keepdims.
  • An np.intp (or an array) is returned otherwise.

The former case is handled by the an identically named function in the np.core._multiarray_umath
module (which apparently always returns an int) while the latter is effectively a wrapper around
np.ndarray.sum() with its dtype explicitly set to np.intp:

numpy/numpy/core/numeric.py

Lines 484 to 495 in 4ccfbe6

if axis is None and not keepdims:
return multiarray.count_nonzero(a)
a = asanyarray(a)
# TODO: this works around .astype(bool) not working properly (gh-9847)
if np.issubdtype(a.dtype, np.character):
a_bool = a != a.dtype.type()
else:
a_bool = a.astype(np.bool_, copy=False)
return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)

Reproducing code example:

MacOS 10.15.6; Python 3.8.5; NumPy 1.20.0.dev0+eb2c751

In [1]: import numpy as np

In [2]: ar = np.arange(10)

In [3]: np.count_nonzero(ar).__class__
Out[3]: int

In [4]: np.count_nonzero(ar, axis=0).__class__
Out[4]: numpy.int64  # i.e. np.intp

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0