Skip to content

Commit 5f11fc1

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

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

hoge.py

Whitespace-only changes.

pandas/core/internals/blocks.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1005,8 +1005,11 @@ 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+
else:
1011+
# if we cannot then coerce to object
1012+
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
10101013

10111014
if is_dtype_equal(self.dtype, dtype):
10121015
return self

pandas/tests/series/methods/test_replace.py

+16
Original file line numberDiff line numberDiff line change
@@ -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)