Skip to content
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
8 changes: 7 additions & 1 deletion pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,13 @@ def _replace_coerce(
"""
if mask.any():
if not regex:
nb = self.coerce_to_target_dtype(value)
if isinstance(self.values, ExtensionArray) and self._can_hold_element(
value
):
nb = self
else:
nb = self.coerce_to_target_dtype(value)

if nb is self and not inplace:
nb = nb.copy()
putmask_inplace(nb.values, mask, value)
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1681,3 +1681,39 @@ def test_replace_bytes(self, frame_or_series):
expected = obj.copy()
obj = obj.replace({None: np.nan})
tm.assert_equal(obj, expected)

@pytest.mark.parametrize(
"data, to_replace, value, expected, dtype",
[
(
[1.0, 2.0, 3.999, 4.4],
1.0,
9,
[9.0, 2.0, 3.999, 4.4],
"Float64",
),
(
[1.0, 2.0, 3.999, 4.4],
1.0,
9.0,
[9.0, 2.0, 3.999, 4.4],
"Float64",
),
([1, 2, 3, 4], 1, 9, [9, 2, 3, 4], "Int64"),
([1, 2, 3, 4], 1, 9.0, [9, 2, 3, 4], "Int64"),
(["a", None, "b"], "a", "1", ["1", None, "b"], "string"),
([None, False, True], True, False, [None, False, False], "boolean"),
],
)
def test_replace_with_nullable_arrays(
self, frame_or_series, data, to_replace, value, expected, dtype
):
# GH40732
obj = frame_or_series(data, dtype=dtype)
expected = frame_or_series(expected, dtype=dtype)

result = obj.replace(to_replace, value)
tm.assert_equal(result, expected)

result = obj.replace({to_replace: value})
tm.assert_equal(result, expected)