Skip to content

Commit 227409c

Browse files
Backport PR pandas-dev#46335: BUG: replace with value also being replaced (pandas-dev#46340)
Co-authored-by: Luke Manley <[email protected]>
1 parent e11dba8 commit 227409c

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
@@ -708,9 +708,18 @@ def replace(
708708

709709
else:
710710
# split so that we only upcast where necessary
711-
return self.split_and_operate(
712-
type(self).replace, to_replace, value, inplace=True
713-
)
711+
blocks = []
712+
for i, nb in enumerate(self._split()):
713+
blocks.extend(
714+
type(self).replace(
715+
nb,
716+
to_replace=to_replace,
717+
value=value,
718+
inplace=True,
719+
mask=mask[i : i + 1],
720+
)
721+
)
722+
return blocks
714723

715724
@final
716725
def _replace_regex(

pandas/tests/frame/methods/test_replace.py

+7
Original file line numberDiff line numberDiff line change
@@ -1519,3 +1519,10 @@ def test_replace_regex_dtype_frame(self, regex):
15191519
expected_df2 = DataFrame({"A": [1], "B": ["1"]})
15201520
result_df2 = df2.replace(to_replace="0", value=1, regex=regex)
15211521
tm.assert_frame_equal(result_df2, expected_df2)
1522+
1523+
def test_replace_with_value_also_being_replaced(self):
1524+
# GH46306
1525+
df = DataFrame({"A": [0, 1, 2], "B": [1, 0, 2]})
1526+
result = df.replace({0: 1, 1: np.nan})
1527+
expected = DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]})
1528+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)