Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6e1d637

Browse files
committed
BUG: Make bool(str_scalar) and str_scalar.astype(bool) consistent
Caused by string values being cast to an int first and then a bool, ie arr.astype(int).astype(bool). This causes crashes on non-numeric strings, and only accepts strings of 0 as false. Fixes #9847
1 parent 3f300ba commit 6e1d637

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

doc/release/1.14.0-notes.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ the result is always a view on the original masked array.
144144
This breaks any code that used ``masked_arr.squeeze() is np.ma.masked``, but
145145
fixes code that writes to the result of `.squeeze()`.
146146

147+
``string.astype(bool)`` now uses the normal python semantics for converting
148+
---------------------------------------------------------------------------
149+
Previously this was interpreted as ``string.astype(int).astype(bool)``, which
150+
interpeted ``'0'`` as ``False``.
151+
152+
The behavior is now consistent with `count_nonzero` and `nonzero`, treating only
153+
the empty string as ``False``.
154+
147155
Renamed first parameter of ``can_cast`` from ``from`` to ``from_``
148156
------------------------------------------------------------------
149157
The previous parameter name ``from`` is a reserved keyword in Python, which made

numpy/core/src/multiarray/arraytypes.c.src

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1545,7 +1545,7 @@ OBJECT_to_@TOTYPE@(void *input, void *output, npy_intp n,
15451545
* #convert = 1*18, 0*3, 1*2,
15461546
* 1*18, 0*3, 1*2,
15471547
* 0*23#
1548-
* #convstr = (Int*9, Long*2, Float*4, Complex*3, Tuple*3, Long*2)*3#
1548+
* #convstr = (Bool, Int*8, Long*2, Float*4, Complex*3, Tuple*3, Long*2)*3#
15491549
*/
15501550

15511551
#if @convert@

numpy/core/tests/test_multiarray.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,11 +1226,9 @@ def _test_cast_from_flexible(self, dtype):
12261226
def test_cast_from_void(self):
12271227
self._test_cast_from_flexible(np.void)
12281228

1229-
@dec.knownfailureif(True, "See gh-9847")
12301229
def test_cast_from_unicode(self):
12311230
self._test_cast_from_flexible(np.unicode_)
12321231

1233-
@dec.knownfailureif(True, "See gh-9847")
12341232
def test_cast_from_bytes(self):
12351233
self._test_cast_from_flexible(np.bytes_)
12361234

0 commit comments

Comments
 (0)