@@ -739,6 +739,13 @@ def _try_coerce_args(self, other):
739
739
type (self ).__name__ .lower ().replace ("Block" , "" ),
740
740
)
741
741
)
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
+ )
742
749
743
750
return other
744
751
@@ -787,16 +794,15 @@ def replace(
787
794
inplace = validate_bool_kwarg (inplace , "inplace" )
788
795
original_to_replace = to_replace
789
796
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
791
798
# 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
796
802
# GH 22083, TypeError or ValueError occurred within error handling
797
803
# causes infinite loop. Cast and retry only if not objectblock.
798
804
if is_object_dtype (self ):
799
- raise
805
+ raise AssertionError
800
806
801
807
# try again with a compatible block
802
808
block = self .astype (object )
@@ -809,6 +815,9 @@ def replace(
809
815
convert = convert ,
810
816
)
811
817
818
+ values = self ._coerce_values (self .values )
819
+ to_replace = self ._try_coerce_args (to_replace )
820
+
812
821
mask = missing .mask_missing (values , to_replace )
813
822
if filter is not None :
814
823
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)
1405
1414
1406
1415
# our where function
1407
1416
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 )
1409
1425
1410
1426
try :
1411
1427
fastres = expressions .where (cond , values , other )
0 commit comments