Skip to content

Commit acb7dd1

Browse files
authored
Merge pull request #2831 from pavlin-policar/util-bincount-allnans
[FIX] Bincount: Fix crash on array with all nans
2 parents f7cbdf8 + a5515a3 commit acb7dd1

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

Orange/statistics/util.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,11 @@ def bincount(x, weights=None, max_val=None, minlength=None):
144144
# zeros, we must count implicit zeros separately and add them to the
145145
# explicit ones found before
146146
if sp.issparse(x_original):
147-
bc[0] += zero_weights
147+
# If x contains only NaNs, then bc will be an empty array
148+
if zero_weights and bc.size == 0:
149+
bc = [zero_weights]
150+
elif zero_weights:
151+
bc[0] += zero_weights
148152

149153
return bc, nans
150154

Orange/tests/test_statistics.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ def sparse_with_explicit_zero(x, array):
2626

2727
return sp_array
2828

29-
test_case(self, lambda x: np.array(x))
29+
test_case(self, np.array)
30+
test_case(self, csr_matrix)
31+
test_case(self, csc_matrix)
3032
test_case(self, partial(sparse_with_explicit_zero, array=csr_matrix))
3133
test_case(self, partial(sparse_with_explicit_zero, array=csc_matrix))
3234

@@ -408,6 +410,22 @@ def test_weights_with_transposed_x(self, array):
408410
expected = [3, 0, 2, 1]
409411
np.testing.assert_equal(bincount(x, w)[0], expected)
410412

413+
@dense_sparse
414+
def test_all_nans(self, array):
415+
x = array([np.nan] * 5)
416+
expected = []
417+
418+
np.testing.assert_equal(bincount(x)[0], expected)
419+
420+
@dense_sparse
421+
def test_all_zeros_or_nans(self, array):
422+
"""Sparse arrays with only nans with no explicit zeros will have no non
423+
zero indices. Check that this counts the zeros properly."""
424+
x = array([np.nan] * 5 + [0] * 5)
425+
expected = [5]
426+
427+
np.testing.assert_equal(bincount(x)[0], expected)
428+
411429

412430
class TestUnique(unittest.TestCase):
413431
@dense_sparse

0 commit comments

Comments
 (0)