Skip to content

Commit d45903e

Browse files
authored
BUG: df.replace over pd.Period columns (#34871) (#36867)
1 parent 05c130d commit d45903e

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

doc/source/whatsnew/v1.2.0.rst

+7
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,8 @@ Strings
562562

563563
Interval
564564
^^^^^^^^
565+
566+
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` where :class:`Interval` dtypes would be converted to object dtypes (:issue:`34871`)
565567
- Bug in :meth:`IntervalIndex.take` with negative indices and ``fill_value=None`` (:issue:`37330`)
566568
-
567569
-
@@ -626,6 +628,11 @@ I/O
626628
- :meth:`to_excel` and :meth:`to_markdown` support writing to fsspec URLs such as S3 and Google Cloud Storage (:issue:`33987`)
627629
- Bug in :meth:`read_fw` was not skipping blank lines (even with ``skip_blank_lines=True``) (:issue:`37758`)
628630

631+
Period
632+
^^^^^^
633+
634+
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` where :class:`Period` dtypes would be converted to object dtypes (:issue:`34871`)
635+
629636
Plotting
630637
^^^^^^^^
631638

pandas/core/internals/blocks.py

+10
Original file line numberDiff line numberDiff line change
@@ -2041,6 +2041,16 @@ class ObjectValuesExtensionBlock(ExtensionBlock):
20412041
def external_values(self):
20422042
return self.values.astype(object)
20432043

2044+
def _can_hold_element(self, element: Any) -> bool:
2045+
if is_valid_nat_for_dtype(element, self.dtype):
2046+
return True
2047+
if isinstance(element, list) and len(element) == 0:
2048+
return True
2049+
tipo = maybe_infer_dtype_type(element)
2050+
if tipo is not None:
2051+
return issubclass(tipo.type, self.dtype.type)
2052+
return isinstance(element, self.dtype.type)
2053+
20442054

20452055
class NumericBlock(Block):
20462056
__slots__ = ()

pandas/tests/frame/methods/test_replace.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -1523,12 +1523,10 @@ def test_replace_with_duplicate_columns(self, replacement):
15231523

15241524
tm.assert_frame_equal(result, expected)
15251525

1526-
def test_replace_period_ignore_float(self, frame_or_series):
1527-
"""
1528-
Regression test for GH#34871: if df.replace(1.0, 0.0) is called on a df
1529-
with a Period column the old, faulty behavior is to raise TypeError.
1530-
"""
1531-
obj = DataFrame({"Per": [pd.Period("2020-01")] * 3})
1526+
@pytest.mark.parametrize("value", [pd.Period("2020-01"), pd.Interval(0, 5)])
1527+
def test_replace_ea_ignore_float(self, frame_or_series, value):
1528+
# GH#34871
1529+
obj = DataFrame({"Per": [value] * 3})
15321530
if frame_or_series is not DataFrame:
15331531
obj = obj["Per"]
15341532

0 commit comments

Comments
 (0)