Skip to content

Commit eeeae46

Browse files
committed
BUG: fix replacer's dtypes not respected for frame replace (pandas-dev#26632)
1 parent ad4c4d5 commit eeeae46

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ Reshaping
466466
- Better error message in :func:`get_dummies` when `columns` isn't a list-like value (:issue:`28383`)
467467
- Bug :meth:`Series.pct_change` where supplying an anchored frequency would throw a ValueError (:issue:`28664`)
468468
- Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`)
469+
- Bug in :meth:`DataFrame.replace` that caused non-numeric replacer's dtype not respected (:issue:`26632`)
469470

470471
Sparse
471472
^^^^^^

pandas/core/internals/blocks.py

+2
Original file line numberDiff line numberDiff line change
@@ -2825,6 +2825,8 @@ def _replace_coerce(
28252825
if convert:
28262826
block = [b.convert(numeric=False, copy=True) for b in block]
28272827
return block
2828+
if convert:
2829+
return [self.convert(numeric=False, copy=True)]
28282830
return self
28292831

28302832

pandas/core/internals/managers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ def comp(s, regex=False):
629629
convert=convert,
630630
regex=regex,
631631
)
632-
if m.any():
632+
if m.any() or convert:
633633
new_rb = _extend_blocks(result, new_rb)
634634
else:
635635
new_rb.append(b)

pandas/tests/frame/test_replace.py

+16
Original file line numberDiff line numberDiff line change
@@ -1338,5 +1338,21 @@ def test_replace_commutative(self, df, to_replace, exp):
13381338

13391339
expected = pd.DataFrame(exp)
13401340
result = df.replace(to_replace)
1341+
tm.assert_frame_equal(result, expected)
13411342

1343+
@pytest.mark.parametrize(
1344+
"replacer",
1345+
[
1346+
pd.Timestamp("20170827"),
1347+
np.int8(1),
1348+
np.int16(1),
1349+
np.float32(1),
1350+
np.float64(1),
1351+
],
1352+
)
1353+
def test_replace_replacer_dtype(self, replacer):
1354+
# GH26632
1355+
df = pd.DataFrame(["a"])
1356+
result = df.replace({"a": replacer, "b": replacer})
1357+
expected = pd.DataFrame([replacer])
13421358
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)