Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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
9 changes: 8 additions & 1 deletion pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,7 +1010,14 @@ def coerce_to_target_dtype(self, other):
if is_dtype_equal(self.dtype, dtype):
return self

if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype):
if (
is_extension_array_dtype(self.dtype)
and not is_categorical_dtype(self.dtype)
Copy link
Contributor

Choose a reason for hiding this comment

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

you can just use is_extension_array_dtype here

and not self.is_datetime
):
dtype = self.dtype

elif self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype):
# we don't upcast to bool
return self.astype(object)

Expand Down
19 changes: 18 additions & 1 deletion pandas/tests/series/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def test_replace2(self):
def test_replace_with_dictlike_and_string_dtype(self):
# GH 32621
s = pd.Series(["one", "two", np.nan], dtype="string")
expected = pd.Series(["1", "2", np.nan])
expected = pd.Series(["1", "2", np.nan], dtype="string")
result = s.replace({"one": "1", "two": "2"})
tm.assert_series_equal(expected, result)

Expand Down Expand Up @@ -402,3 +402,20 @@ def test_replace_only_one_dictlike_arg(self):
msg = "Series.replace cannot use dict-value and non-None to_replace"
with pytest.raises(ValueError, match=msg):
ser.replace(to_replace, value)

@pytest.mark.parametrize(
"series, to_replace, expected",
[
(
pd.Series(["one", "two"], dtype="string"),
{"one": "1", "two": "2"},
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add a bunch more tests which can hit the other EA types, e.g. Intervval, Period, Datetime w/tz

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added test cases.

"string",
),
(pd.Series([1, 2], dtype="int64"), {1: 10, 2: 20}, "int64"),
(pd.Series([True, False], dtype="bool"), {True: False}, "bool"),
],
)
def test_replace_dtype(self, series, to_replace, expected):
# GH 33484
result = str(series.replace(to_replace).dtype)
assert expected == result