Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/indexes/period/methods/test_asfreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
)
import pandas._testing as tm

from pandas.tseries import offsets


class TestPeriodIndex:
def test_asfreq(self):
Expand Down Expand Up @@ -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)