From c792056a90c3abcf99336062db10bc501754f7e0 Mon Sep 17 00:00:00 2001 From: Natalia Mokeeva Date: Thu, 25 Jan 2024 23:12:51 +0100 Subject: [PATCH] correct PeriodIndex.asfreq, add tests --- pandas/core/indexes/period.py | 14 +++++++++++++- .../tests/indexes/period/methods/test_asfreq.py | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index b2f1933800fd3..563c4308d8d43 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -17,7 +17,10 @@ Resolution, Tick, ) -from pandas._libs.tslibs.dtypes import OFFSET_TO_PERIOD_FREQSTR +from pandas._libs.tslibs.dtypes import ( + OFFSET_TO_PERIOD_FREQSTR, + freq_to_period_freqstr, +) from pandas.util._decorators import ( cache_readonly, doc, @@ -205,6 +208,15 @@ def _resolution_obj(self) -> Resolution: **_shared_doc_kwargs, ) def asfreq(self, freq=None, how: str = "E") -> Self: + if isinstance(freq, BaseOffset): + if hasattr(freq, "_period_dtype_code"): + freq = freq_to_period_freqstr(freq.n, freq.name) + else: + raise ValueError( + f"Invalid offset: '{freq.base}' for converting time series " + f"with PeriodIndex." + ) + arr = self._data.asfreq(freq, how) return type(self)._simple_new(arr, name=self.name) diff --git a/pandas/tests/indexes/period/methods/test_asfreq.py b/pandas/tests/indexes/period/methods/test_asfreq.py index ed078a3e8fb8b..2d5214e8578ee 100644 --- a/pandas/tests/indexes/period/methods/test_asfreq.py +++ b/pandas/tests/indexes/period/methods/test_asfreq.py @@ -7,6 +7,8 @@ ) import pandas._testing as tm +from pandas.tseries import offsets + class TestPeriodIndex: def test_asfreq(self): @@ -136,3 +138,18 @@ def test_asfreq_with_different_n(self): excepted = Series([1, 2], index=PeriodIndex(["2020-02", "2020-04"], freq="M")) tm.assert_series_equal(result, excepted) + + @pytest.mark.parametrize( + "freq", + [ + offsets.MonthBegin(2), + offsets.BusinessMonthEnd(2), + ], + ) + def test_pi_asfreq_invalid_baseoffset(self, freq): + # GH#55785 + msg = f"Invalid offset: '{freq.base}' for converting time series " + + pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M") + with pytest.raises(ValueError, match=msg): + pi.asfreq(freq=freq)