Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
5 changes: 5 additions & 0 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,11 +732,16 @@ def asfreq(self, freq=None, how: str = "E") -> Self:
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]')
"""
freq_str = freq if isinstance(freq, str) else freq.freqstr

how = libperiod.validate_end_alias(how)
if isinstance(freq, BaseOffset):
freq = freq_to_period_freqstr(freq.n, freq.name)
freq = Period._maybe_convert_freq(freq)

if not hasattr(freq, "_period_dtype_code"):
raise TypeError(f'"{freq_str}" is not supported as a period frequency')

base1 = self._dtype._dtype_code
base2 = freq._period_dtype_code

Expand Down
34 changes: 34 additions & 0 deletions pandas/tests/frame/methods/test_asfreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pandas import (
DataFrame,
DatetimeIndex,
PeriodIndex,
Series,
date_range,
period_range,
Expand Down Expand Up @@ -257,3 +258,36 @@ def test_asfreq_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr):
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
result = df.asfreq(freq=freq_depr)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize(
"freq, error, error_msg",
[
(
"2MS",
TypeError,
'"2MS" is not supported as a period frequency',
),
(
offsets.MonthBegin(),
ValueError,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like those are caught before they reach your new error?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noting that Patrick and I chatted over Slack. Summary: The change in this PR raises an error for invalid strings. Another part of the code raises errors for for invalid offsets (That was already implemented, before this PR).

(
"Invalid offset: '<MonthBegin>' for converting "
"time series with PeriodIndex."
),
),
(
offsets.DateOffset(months=2),
ValueError,
(
"Invalid offset: '<DateOffset: months=2>' for converting "
"time series with PeriodIndex."
),
),
],
)
def test_asfreq_unsupported_freq(self, freq, error, error_msg):
index = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
df = DataFrame({"a": Series([0, 1], index=index)})

with pytest.raises(error, match=error_msg):
df.asfreq(freq=freq)