Skip to content

ENH: raise ValueError if invalid period freq pass to asfreq when the index of df is a PeriodIndex #56945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
5 changes: 4 additions & 1 deletion pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4846,7 +4846,7 @@ cpdef to_offset(freq, bint is_period=False):
)

elif PyDelta_Check(freq):
return delta_to_tick(freq)
delta = delta_to_tick(freq)
Copy link
Member

Choose a reason for hiding this comment

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

maybe on line 4841, we can do

    if isinstance(freq, BaseOffset):
        delta = freq

so then that gets validated too?

Copy link
Member

Choose a reason for hiding this comment

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

is it possible to do this assignment on line 4841 as well? just in case an offset which isn't valid for periods is passed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am unsure if it's possible. I tried to do this assignment on line 4841

if isinstance(freq, BaseOffset):
    delta = freq

but then I got failures.
The reason: if we replace return freq with the delta = freq, we go to the line 4962 and assign delta to None and then on line 4965 we raise a ValueError.
Which is why instead of the assignment delta = freq I added the check

if is_period and not hasattr(freq, "_period_dtype_code"):
    raise ValueError(f"{freq.base} is not supported as period frequency")

Copy link
Member

Choose a reason for hiding this comment

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

I think you can just move this down to before elif PyDelta_Check(freq):

Copy link
Contributor Author

Choose a reason for hiding this comment

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

thanks, I saw you already made commit for it


elif isinstance(freq, str):
delta = None
Expand Down Expand Up @@ -4964,6 +4964,9 @@ cpdef to_offset(freq, bint is_period=False):
if delta is None:
raise ValueError(INVALID_FREQ_ERR_MSG.format(freq))

if is_period and not hasattr(delta, "_period_dtype_code"):
raise ValueError(INVALID_FREQ_ERR_MSG.format(freq))

return delta


Expand Down
7 changes: 6 additions & 1 deletion pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@
Period,
Resolution,
Tick,
to_offset,
)
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._libs.tslibs.period import INVALID_FREQ_ERR_MSG
from pandas.util._decorators import (
cache_readonly,
doc,
Expand Down
22 changes: 21 additions & 1 deletion pandas/tests/indexes/period/methods/test_asfreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def test_asfreq(self):

msg = "How must be one of S or E"
with pytest.raises(ValueError, match=msg):
pi7.asfreq("T", "foo")
pi7.asfreq("min", "foo")
result1 = pi1.asfreq("3M")
result2 = pi1.asfreq("M")
expected = period_range(freq="M", start="2001-12", end="2001-12")
Expand Down Expand Up @@ -136,3 +136,23 @@ 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",
[
"2BMS",
"2YS-MAR",
"2bh",
"2BME",
"2YE-MAR",
"2BM",
"2QE",
],
)
def test_pi_asfreq_invalid_frequency(self, freq):
# GH#55785
msg = f"Invalid frequency: {freq}"

pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
with pytest.raises(ValueError, match=msg):
pi.asfreq(freq=freq)
4 changes: 2 additions & 2 deletions pandas/tests/resample/test_period_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1032,8 +1032,8 @@ def test_resample_lowercase_frequency_deprecated(
offsets.BusinessHour(2),
],
)
def test_asfreq_invalid_period_freq(self, offset, frame_or_series):
# GH#9586
def test_asfreq_invalid_period_offset(self, offset, frame_or_series):
# GH#55785
msg = f"Invalid offset: '{offset.base}' for converting time series "

obj = frame_or_series(range(5), index=period_range("2020-01-01", periods=5))
Expand Down