8000 `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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
BvB93 opened this issue Oct 14, 2020 · 0 comments
Open

count_nonzero can return either a builtin int or numpy's intp #17562

BvB93 opened this issue Oct 14, 2020 · 0 comments

Comments

@BvB93
Copy link
Member
BvB93 commented Oct 14, 2020

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
@BvB93 BvB93 changed the title BUG: count_nonzero can return either a builtin int or numpy's intp count_nonzero can return either a builtin int or numpy's intp Sep 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant
0