diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 98d861d999ea9..bfc5cac7339ca 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -466,6 +466,7 @@ Reshaping - Better error message in :func:`get_dummies` when `columns` isn't a list-like value (:issue:`28383`) - Bug :meth:`Series.pct_change` where supplying an anchored frequency would throw a ValueError (:issue:`28664`) - Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`) +- Bug in :meth:`DataFrame.replace` that caused non-numeric replacer's dtype not respected (:issue:`26632`) Sparse ^^^^^^ diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7ace80415c846..5edb4d93e068a 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2825,6 +2825,8 @@ def _replace_coerce( if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block + if convert: + return [self.convert(numeric=False, copy=True)] return self diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 0e6ba8a2c2a6a..c36dd9463c61d 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -629,7 +629,7 @@ def comp(s, regex=False): convert=convert, regex=regex, ) - if m.any(): + if m.any() or convert: new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index 60b601b57e007..434ea6ea7b4f0 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -1338,5 +1338,21 @@ def test_replace_commutative(self, df, to_replace, exp): expected = pd.DataFrame(exp) result = df.replace(to_replace) + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "replacer", + [ + pd.Timestamp("20170827"), + np.int8(1), + np.int16(1), + np.float32(1), + np.float64(1), + ], + ) + def test_replace_replacer_dtype(self, replacer): + # GH26632 + df = pd.DataFrame(["a"]) + result = df.replace({"a": replacer, "b": replacer}) + expected = pd.DataFrame([replacer]) tm.assert_frame_equal(result, expected)