Skip to content

Commit 9ef9f9e

Browse files
committed
BUG: pd.Series.replace does not preserve the original dtype
1 parent 3d4f9dc commit 9ef9f9e

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

pandas/core/internals/blocks.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -1005,8 +1005,15 @@ def coerce_to_target_dtype(self, other):
10051005
we can also safely try to coerce to the same dtype
10061006
and will receive the same block
10071007
"""
1008-
# if we cannot then coerce to object
1009-
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
1008+
if type(other) == str:
1009+
dtype = "string"
1010+
if is_dtype_equal(self.dtype, dtype):
1011+
return self
1012+
else:
1013+
dtype = np.object_
1014+
else:
1015+
# if we cannot then coerce to object
1016+
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
10101017

10111018
if is_dtype_equal(self.dtype, dtype):
10121019
return self

pandas/tests/series/methods/test_replace.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def test_replace2(self):
254254
def test_replace_with_dictlike_and_string_dtype(self):
255255
# GH 32621
256256
s = pd.Series(["one", "two", np.nan], dtype="string")
257-
expected = pd.Series(["1", "2", np.nan])
257+
expected = pd.Series(["1", "2", np.nan], dtype="string")
258258
result = s.replace({"one": "1", "two": "2"})
259259
tm.assert_series_equal(expected, result)
260260

@@ -406,3 +406,19 @@ def test_replace_only_one_dictlike_arg(self):
406406
msg = "Series.replace cannot use dict-value and non-None to_replace"
407407
with pytest.raises(ValueError, match=msg):
408408
ser.replace(to_replace, value)
409+
410+
@pytest.mark.parametrize(
411+
"series, to_replace, expected",
412+
[
413+
(
414+
pd.Series(["one", "two"], dtype="string"),
415+
{"one": "1", "two": "2"},
416+
"string",
417+
),
418+
(pd.Series([1, 2], dtype="int64"), {1: 10, 2: 20}, "int64"),
419+
(pd.Series([True, False], dtype="bool"), {True: False}, "bool"),
420+
],
421+
)
422+
def test_replace_dtype(self, series, to_replace, expected):
423+
result = str(series.replace(to_replace).dtype)
424+
assert expected == result

0 commit comments

Comments
 (0)