Skip to content

Commit

Permalink
Bug in DataFrame.replace casts columns to object dtype if items i…
Browse files Browse the repository at this point in the history
…n ``to_replace`` not in values (pandas-dev#34048)
  • Loading branch information
simonjayhawkins authored and rhshadrach committed May 10, 2020
1 parent 9dbbe30 commit 2cbac0c
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 5 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,7 @@ Reshaping
- Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`)
- Bug in :func:`concat` was not allowing for concatenation of ``DataFrame`` and ``Series`` with duplicate keys (:issue:`33654`)
- Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`)
- Bug in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)


Sparse
Expand Down
5 changes: 0 additions & 5 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,11 +728,6 @@ def replace(

mask = missing.mask_missing(values, to_replace)

if not mask.any():
if inplace:
return [self]
return [self.copy()]

try:
blocks = self.putmask(mask, value, inplace=inplace)
# Note: it is _not_ the case that self._can_hold_element(value)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,3 +1380,11 @@ def test_replace_invalid_to_replace(self):
)
with pytest.raises(TypeError, match=msg):
df.replace(lambda x: x.strip())

@pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"])
@pytest.mark.parametrize("value", [np.nan, pd.NA])
def test_replace_no_replacement_dtypes(self, dtype, value):
# https://github.com/pandas-dev/pandas/issues/32988
df = pd.DataFrame(np.eye(2), dtype=dtype)
result = df.replace(to_replace=[None, -np.inf, np.inf], value=value)
tm.assert_frame_equal(result, df)

0 comments on commit 2cbac0c

Please sign in to comment.