Skip to content

BUG: replace with value also being replaced #46335

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

Merged
merged 5 commits into from
Mar 12, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 9 additions & 3 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,15 @@ def replace(

else:
# split so that we only upcast where necessary
return self.split_and_operate(
type(self).replace, to_replace, value, inplace=True
)
blocks = []
nbs = self._split()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could write this entire section as a list-comprehension, but maybe not as readable

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good idea, i like the list comprehension better

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went back to a non-list comprehension implementation as it requires unpacking.

for i, nb in enumerate(nbs):
submask = mask[i]
rbs = type(self).replace(
nb, to_replace, value, inplace=True, mask=submask
)
blocks.extend(rbs)
return blocks

@final
def _replace_regex(
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1542,3 +1542,10 @@ def test_replace_regex_dtype_frame(self, regex):
expected_df2 = DataFrame({"A": [1], "B": ["1"]})
result_df2 = df2.replace(to_replace="0", value=1, regex=regex)
tm.assert_frame_equal(result_df2, expected_df2)

def test_replace_with_value_also_being_replaced(self):
# GH46306
df = DataFrame({"A": [0, 1, 2], "B": [1, 0, 2]})
result = df.replace({0: 1, 1: np.nan})
expected = DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]})
tm.assert_frame_equal(result, expected)