8000 BUG: count_nonzero treats empty axis tuples strangely · eric-wieser/numpy@3856a73 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3856a73

Browse files
committed
BUG: count_nonzero treats empty axis tuples strangely
Fixes numpy#9728 This bug was introduced with the `axis` keyword in numpy#7177, as a misguided optimization.
1 parent 77f9540 commit 3856a73

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/release/1.14.0-notes.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,13 @@ passed, despite not doing so under the simple cases::
122122

123123
This change affects only ``float32`` and ``float16`` arrays.
124124

125+
``count_nonzero(arr, axis=())`` now counts over no axes, not all axes
126+
---------------------------------------------------------------------
127+
Elsewhere, ``axis==()`` is always understood as "no axes", but
128+
`count_nonzero` had a special case to treat this as "all axes". This was
129+
inconsistent and surprising. The correct way to count over all axes has always
130+
been to pass ``axis == None``.
131+
125132
``__init__.py`` files added to test directories
126133
-----------------------------------------------
127134
This is for pytest compatibility in the case of duplicate test file names in

numpy/core/numeric.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ def count_nonzero(a, axis=None):
406406
array([2, 3])
407407
408408
"""
409-
if axis is None or (isinstance(axis, tuple) and axis == ()):
409+
if axis is None:
410410
return multiarray.count_nonzero(a)
411411

412412
a = asanyarray(a)

numpy/core/tests/test_numeric.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,10 @@ def test_count_nonzero_axis_consistent(self):
11261126
np.count_nonzero(n, axis=perm),
11271127
err_msg=msg % (perm,))
11281128

1129+
def test_countnonzero_axis_empty(self):
1130+
a = np.array([[0, 0, 1], [1, 0, 1]])
1131+
assert_equal(np.count_nonzero(a, axis=()), a.astype(bool))
1132+
11291133
def test_array_method(self):
11301134
# Tests that the array method
11311135
# call to nonzero works

0 commit comments

Comments
 (0)
0