Skip to content

Commit 80b5bc6

Browse files
Reorder tests in maybe_downcast_numeric
The comment `# if we have any nulls, then we are done` is not consistent with the test `if isna(arr).any()` because `arr` is constructed only from the first element (`r[0]`) not the full ravel'd list of values. Moreover, calling `np.array()` on some random type can have surprising consequences. So instead, do the early-out test as intended, just using `r[0]` without going through `np.array()`. Then test other things about `r[0]`. Only then should we test all the values (and if we have any nulls, then we are done). See pandas-dev#55824 Signed-off-by: Michael Tiemann <[email protected]>
1 parent c2cdeaf commit 80b5bc6

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

pandas/core/dtypes/cast.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -357,18 +357,20 @@ def trans(x):
357357
# if we don't have any elements, just astype it
358358
return trans(result).astype(dtype)
359359

360-
# do a test on the first element, if it fails then we are done
361360
r = result.ravel()
362-
arr = np.array([r[0]])
363361

364-
if isna(arr).any():
365-
# if we have any nulls, then we are done
362+
if isna(r[0]):
363+
# do a test on the first element, if it fails then we are done
366364
return result
367365

368366
elif not isinstance(r[0], (np.integer, np.floating, int, float, bool)):
369367
# a comparable, e.g. a Decimal may slip in here
370368
return result
371369

370+
if isna(r).any():
371+
# if we have any nulls, then we are done
372+
return result
373+
372374
if (
373375
issubclass(result.dtype.type, (np.object_, np.number))
374376
and notna(result).all()

0 commit comments

Comments
 (0)