Skip to content

Commit 25f9b4e

Browse files
authored
REF: avoid try/except in Block.where (#37802)
1 parent fe6d55c commit 25f9b4e

File tree

1 file changed

+22
-23
lines changed

1 file changed

+22
-23
lines changed

pandas/core/internals/blocks.py

+22-23
Original file line numberDiff line numberDiff line change
@@ -1442,34 +1442,21 @@ def where(
14421442
if not hasattr(cond, "shape"):
14431443
raise ValueError("where must have a condition that is ndarray like")
14441444

1445-
def where_func(cond, values, other):
1446-
1447-
if not (
1448-
(self.is_integer or self.is_bool)
1449-
and lib.is_float(other)
1450-
and np.isnan(other)
1451-
):
1452-
# np.where will cast integer array to floats in this case
1453-
if not self._can_hold_element(other):
1454-
raise TypeError
1455-
if lib.is_scalar(other) and isinstance(values, np.ndarray):
1456-
# convert datetime to datetime64, timedelta to timedelta64
1457-
other = convert_scalar_for_putitemlike(other, values.dtype)
1458-
1459-
# By the time we get here, we should have all Series/Index
1460-
# args extracted to ndarray
1461-
fastres = expressions.where(cond, values, other)
1462-
return fastres
1463-
14641445
if cond.ravel("K").all():
14651446
result = values
14661447
else:
14671448
# see if we can operate on the entire block, or need item-by-item
14681449
# or if we are a single block (ndim == 1)
1469-
try:
1470-
result = where_func(cond, values, other)
1471-
except TypeError:
1472-
1450+
if (
1451+
(self.is_integer or self.is_bool)
1452+
and lib.is_float(other)
1453+
and np.isnan(other)
1454+
):
1455+
# GH#3733 special case to avoid object-dtype casting
1456+
# and go through numexpr path instead.
1457+
# In integer case, np.where will cast to floats
1458+
pass
1459+
elif not self._can_hold_element(other):
14731460
# we cannot coerce, return a compat dtype
14741461
# we are explicitly ignoring errors
14751462
block = self.coerce_to_target_dtype(other)
@@ -1478,6 +1465,18 @@ def where_func(cond, values, other):
14781465
)
14791466
return self._maybe_downcast(blocks, "infer")
14801467

1468+
if not (
1469+
(self.is_integer or self.is_bool)
1470+
and lib.is_float(other)
1471+
and np.isnan(other)
1472+
):
1473+
# convert datetime to datetime64, timedelta to timedelta64
1474+
other = convert_scalar_for_putitemlike(other, values.dtype)
1475+
1476+
# By the time we get here, we should have all Series/Index
1477+
# args extracted to ndarray
1478+
result = expressions.where(cond, values, other)
1479+
14811480
if self._can_hold_na or self.ndim == 1:
14821481

14831482
if transpose:

0 commit comments

Comments
 (0)