8000 Merge pull request #12108 from AetherUnbound/bugfix/12107 · numpy/numpy@41d2428 · GitHub
[go: up one dir, main page]

Skip to content

Commit 41d2428

Browse files
authored
Merge pull request #12108 from AetherUnbound/bugfix/12107
BUG: Allow boolean subtract in histogram
2 parents 9942b71 + e4e897f commit 41d2428

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

numpy/lib/histograms.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,14 @@ def _hist_bin_auto(x):
220220
def _ravel_and_check_weights(a, weights):
221221
""" Check a and weights have matching shapes, and ravel both """
222222
a = np.asarray(a)
223+
224+
# Ensure that the array is a "subtractable" dtype
225+
if a.dtype == np.bool_:
226+
warnings.warn("Converting input from {} to {} for compatibility."
227+
.format(a.dtype, np.uint8),
228+
RuntimeWarning, stacklevel=2)
229+
a = a.astype(np.uint8)
230+
223231
if weights is not None:
224232
weights = np.asarray(weights)
225233
if weights.shape != a.shape:

numpy/lib/tests/test_histograms.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,23 @@ def test_f32_rounding(self):
141141
counts_hist, xedges, yedges = np.histogram2d(x, y, bins=100)
142142
assert_equal(counts_hist.sum(), 3.)
143143

144+
def test_bool_conversion(self):
145+
# gh-12107
146+
# Reference integer histogram
147+
a = np.array([1, 1, 0], dtype=np.uint8)
148+
int_hist, int_edges = np.histogram(a)
149+
150+
# Should raise an warning on booleans
151+
# Ensure that the histograms are equivalent, need to suppress
152+
# the warnings to get the actual outputs
153+
with suppress_warnings() as sup:
154+
rec = sup.record(RuntimeWarning, 'Converting input from .*')
155+
hist, edges = np.histogram([True, True, False])
156+
# A warning should be issued
157+
assert_equal(len(rec), 1)
158+
assert_array_equal(hist, int_hist)
159+
assert_array_equal(edges, int_edges)
160+
144161
def test_weights(self):
145162
v = np.random.rand(100)
146163
w = np.ones(100) * 5

0 commit comments

Comments
 (0)
0