Skip to content

Commit 4ee86a7

Browse files
Reorder tests in maybe_downcast_numeric (#55825)
* 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 #55824 Signed-off-by: Michael Tiemann <[email protected]> * Simplify/optimize tests for downcasting If the first element of `result` is an array, ravel that to get element we will test. Otherwise use it as is. We only need to check whether `result` is all non-null once. Signed-off-by: Michael Tiemann <[email protected]> * Update cast.py Don't use deprecated array indexing on ExtensionArrays. We need to now us `iloc`. Signed-off-by: Michael Tiemann <[email protected]> * Eliminate need to call `ravel` When processing a multidimensional `ndarray`, we can get the first element by calling `result.item(0)` and completely avoid the copying needed by `ravel` to get the first element that way. We can also eliminates an additional conditional check. Signed-off-by: Michael Tiemann <[email protected]> --------- Signed-off-by: Michael Tiemann <[email protected]> Co-authored-by: Richard Shadrach <[email protected]>
1 parent 18f7daf commit 4ee86a7

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

pandas/core/dtypes/cast.py

+5-9
Original file line numberDiff line numberDiff line change
@@ -361,15 +361,11 @@ def trans(x):
361361
# if we don't have any elements, just astype it
362362
return trans(result).astype(dtype)
363363

364-
# do a test on the first element, if it fails then we are done
365-
r = result.ravel()
366-
arr = np.array([r[0]])
367-
368-
if isna(arr).any():
369-
# if we have any nulls, then we are done
370-
return result
371-
372-
elif not isinstance(r[0], (np.integer, np.floating, int, float, bool)):
364+
if isinstance(result, np.ndarray):
365+
element = result.item(0)
366+
else:
367+
element = result.iloc[0]
368+
if not isinstance(element, (np.integer, np.floating, int, float, bool)):
373369
# a comparable, e.g. a Decimal may slip in here
374370
return result
375371

0 commit comments

Comments
 (0)