Skip to content

Commit 0be6fd3

Browse files
authored
BUG: replace with value also being replaced (#46335)
1 parent cf5c2d3 commit 0be6fd3

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

doc/source/whatsnew/v1.4.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Fixed regressions
1818
- Fixed regression in :func:`read_csv` killing python process when invalid file input was given for ``engine="c"`` (:issue:`45957`)
1919
- Fixed memory performance regression in :meth:`Series.fillna` when called on a :class:`DataFrame` column with ``inplace=True`` (:issue:`46149`)
2020
- Provided an alternative solution for passing custom Excel formats in :meth:`.Styler.to_excel`, which was a regression based on stricter CSS validation. Examples available in the documentation for :meth:`.Styler.format` (:issue:`46152`)
21+
- Fixed regression in :meth:`DataFrame.replace` when a replacement value was also a target for replacement (:issue:`46335`)
2122
- Fixed regression in :meth:`DataFrame.loc.__setitem__` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
2223
-
2324

pandas/core/internals/blocks.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -612,9 +612,18 @@ def replace(
612612

613613
else:
614614
# split so that we only upcast where necessary
615-
return self.split_and_operate(
616-
type(self).replace, to_replace, value, inplace=True
617-
)
615+
blocks = []
616+
for i, nb in enumerate(self._split()):
617+
blocks.extend(
618+
type(self).replace(
619+
nb,
620+
to_replace=to_replace,
621+
value=value,
622+
inplace=True,
623+
mask=mask[i : i + 1],
624+
)
625+
)
626+
return blocks
618627

619628
@final
620629
def _replace_regex(

pandas/tests/frame/methods/test_replace.py

+7
Original file line numberDiff line numberDiff line change
@@ -1542,3 +1542,10 @@ def test_replace_regex_dtype_frame(self, regex):
15421542
expected_df2 = DataFrame({"A": [1], "B": ["1"]})
15431543
result_df2 = df2.replace(to_replace="0", value=1, regex=regex)
15441544
tm.assert_frame_equal(result_df2, expected_df2)
1545+
1546+
def test_replace_with_value_also_being_replaced(self):
1547+
# GH46306
1548+
df = DataFrame({"A": [0, 1, 2], "B": [1, 0, 2]})
1549+
result = df.replace({0: 1, 1: np.nan})
1550+
expected = DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]})
1551+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)