Skip to content

BUG: pd.replace changes dtype when using a dict to replace values even when there are no matches #53968

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,7 @@ Other
- Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`)
- Bug in :func:`assert_frame_equal` checks category dtypes even when asked not to check index type (:issue:`52126`)
- Bug in :meth:`DataFrame.reindex` with a ``fill_value`` that should be inferred with a :class:`ExtensionDtype` incorrectly inferring ``object`` dtype (:issue:`52586`)
- Bug in :meth:`DataFrame.replace` changing column dtypes even when no replacements are made (:issue:`53539`)
- Bug in :meth:`DataFrame.shift` and :meth:`Series.shift` when passing both "freq" and "fill_value" silently ignoring "fill_value" instead of raising ``ValueError`` (:issue:`53832`)
- Bug in :meth:`DataFrame.shift` with ``axis=1`` on a :class:`DataFrame` with a single :class:`ExtensionDtype` column giving incorrect results (:issue:`53832`)
- Bug in :meth:`Series.align`, :meth:`DataFrame.align`, :meth:`Series.reindex`, :meth:`DataFrame.reindex`, :meth:`Series.interpolate`, :meth:`DataFrame.interpolate`, incorrectly failing to raise with method="asfreq" (:issue:`53620`)
Expand Down
18 changes: 18 additions & 0 deletions pandas/core/array_algos/replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
if TYPE_CHECKING:
from pandas._typing import (
ArrayLike,
NDFrame,
Scalar,
npt,
)
Expand Down Expand Up @@ -150,3 +151,20 @@ def re_replacer(s):
values[:] = f(values)
else:
values[mask] = f(values[mask])


def keep_original_dtypes(result: NDFrame, original: NDFrame) -> NDFrame:
"""
Keep same data types as the original input if no replacements have been made.

Parameters
----------
result: NDFrame
original: NDFrame
"""
# Perform operation only if input is a dataframe, not a series
if hasattr(original, "columns"):
for col in original.columns:
if result[col].astype(str).equals(original[col].astype(str)):
result[col] = result[col].astype(original[col].dtypes)
return result
13 changes: 12 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@
nanops,
sample,
)
from pandas.core.array_algos.replace import should_use_regex
from pandas.core.array_algos.replace import (
keep_original_dtypes,
should_use_regex,
)
from pandas.core.arrays import ExtensionArray
from pandas.core.base import PandasObject
from pandas.core.construction import extract_array
Expand Down Expand Up @@ -7594,6 +7597,12 @@ def replace(
)

inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
# When replace is called on a copy of a dataframe with inplace set to True,
# self gets overridden when new_data is generated. This allows for a copy
# of the original dataframe to be retained, so if there are no replacements
# the original data types can be kept and returned
original_df = self.copy()
if not is_bool(regex) and to_replace is not None:
raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")

Expand Down Expand Up @@ -7763,8 +7772,10 @@ def replace(

result = self._constructor_from_mgr(new_data, axes=new_data.axes)
if inplace:
result = keep_original_dtypes(result, original_df)
return self._update_inplace(result)
else:
result = keep_original_dtypes(result, self)
return result.__finalize__(self, method="replace")

@final
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,12 @@ def test_replace_with_nil_na(self):
result = ser.replace("nil", "anything else")
tm.assert_frame_equal(expected, result)

def test_replace_no_replacements_dtypes(self):
# GH 53539
df = DataFrame({"a": [1, 2], "b": [3, 4]}, dtype="object")
res = df.replace({5: 0})
tm.assert_frame_equal(df, res)


class TestDataFrameReplaceRegex:
@pytest.mark.parametrize(
Expand Down