Skip to content

Commit d09f20e

Browse files
Bug in DataFrame.replace casts columns to object dtype if items in to_replace not in values (#34048)
1 parent ddbeca6 commit d09f20e

File tree

3 files changed

+9
-5
lines changed

3 files changed

+9
-5
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,7 @@ Reshaping
751751
- Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`)
752752
- Bug in :func:`concat` was not allowing for concatenation of ``DataFrame`` and ``Series`` with duplicate keys (:issue:`33654`)
753753
- Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`)
754+
- Bug in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
754755

755756

756757
Sparse

pandas/core/internals/blocks.py

-5
Original file line numberDiff line numberDiff line change
@@ -728,11 +728,6 @@ def replace(
728728

729729
mask = missing.mask_missing(values, to_replace)
730730

731-
if not mask.any():
732-
if inplace:
733-
return [self]
734-
return [self.copy()]
735-
736731
try:
737732
blocks = self.putmask(mask, value, inplace=inplace)
738733
# Note: it is _not_ the case that self._can_hold_element(value)

pandas/tests/frame/methods/test_replace.py

+8
Original file line numberDiff line numberDiff line change
@@ -1380,3 +1380,11 @@ def test_replace_invalid_to_replace(self):
13801380
)
13811381
with pytest.raises(TypeError, match=msg):
13821382
df.replace(lambda x: x.strip())
1383+
1384+
@pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"])
1385+
@pytest.mark.parametrize("value", [np.nan, pd.NA])
1386+
def test_replace_no_replacement_dtypes(self, dtype, value):
1387+
# https://github.com/pandas-dev/pandas/issues/32988
1388+
df = pd.DataFrame(np.eye(2), dtype=dtype)
1389+
result = df.replace(to_replace=[None, -np.inf, np.inf], value=value)
1390+
tm.assert_frame_equal(result, df)

0 commit comments

Comments
 (0)