Skip to content

Commit 8b676fb

Browse files
jbrockmendelquintusdias
authored andcommitted
CLN: get parts of Block.replace out of try/except (pandas-dev#27408)
1 parent 3e5f362 commit 8b676fb

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

pandas/core/internals/blocks.py

+23-7
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,13 @@ def _try_coerce_args(self, other):
739739
type(self).__name__.lower().replace("Block", ""),
740740
)
741741
)
742+
if np.any(isna(other)) and not self._can_hold_na:
743+
raise TypeError(
744+
"cannot convert {} to an {}".format(
745+
type(other).__name__,
746+
type(self).__name__.lower().replace("Block", ""),
747+
)
748+
)
742749

743750
return other
744751

@@ -787,16 +794,15 @@ def replace(
787794
inplace = validate_bool_kwarg(inplace, "inplace")
788795
original_to_replace = to_replace
789796

790-
# try to replace, if we raise an error, convert to ObjectBlock and
797+
# If we cannot replace with own dtype, convert to ObjectBlock and
791798
# retry
792-
values = self._coerce_values(self.values)
793-
try:
794-
to_replace = self._try_coerce_args(to_replace)
795-
except (TypeError, ValueError):
799+
if not self._can_hold_element(to_replace):
800+
# TODO: we should be able to infer at this point that there is
801+
# nothing to replace
796802
# GH 22083, TypeError or ValueError occurred within error handling
797803
# causes infinite loop. Cast and retry only if not objectblock.
798804
if is_object_dtype(self):
799-
raise
805+
raise AssertionError
800806

801807
# try again with a compatible block
802808
block = self.astype(object)
@@ -809,6 +815,9 @@ def replace(
809815
convert=convert,
810816
)
811817

818+
values = self._coerce_values(self.values)
819+
to_replace = self._try_coerce_args(to_replace)
820+
812821
mask = missing.mask_missing(values, to_replace)
813822
if filter is not None:
814823
filtered_out = ~self.mgr_locs.isin(filter)
@@ -1405,7 +1414,14 @@ def where(self, other, cond, align=True, errors="raise", try_cast=False, axis=0)
14051414

14061415
# our where function
14071416
def func(cond, values, other):
1408-
other = self._try_coerce_args(other)
1417+
1418+
if not (
1419+
(self.is_integer or self.is_bool)
1420+
and lib.is_scalar(other)
1421+
and np.isnan(other)
1422+
):
1423+
# np.where will cast integer array to floats in this case
1424+
other = self._try_coerce_args(other)
14091425

14101426
try:
14111427
fastres = expressions.where(cond, values, other)

0 commit comments

Comments
 (0)