ENH: raise ValueError if invalid period freq pass to asfreq when the index of df is a PeriodIndex by natmokval · Pull Request #56945 · pandas-dev/pandas (original) (raw)

xref #55785, #52064

PeriodIndex.asfreq silently converts for offsets such as offsets.MonthBegin(), offsets.BusinessMonthEnd(), etc. (with no attribute '_period_dtype_code') frequency to period frequency (in this case 'M').

Reproducible Example:

>>> import pandas as pd
>>> from pandas.tseries import offsets
>>>
>>> index = pd.PeriodIndex(["2020-01-01", "2021-01-01"], freq="Q")
>>> index.asfreq(freq=offsets.MonthBegin(1))
PeriodIndex(['2020-03', '2021-03'], dtype='period[M]')
>>>
>>> index.asfreq(freq=offsets.BusinessMonthEnd(1)) 
PeriodIndex(['2020-03', '2021-03'], dtype='period[M]')

the correct behaviour would be raising an Error:

>>> index.asfreq(freq=offsets.MonthBegin(1))
ValueError: <MonthBegin> is not supported as period frequency

Another problem: so far in the example below

>>> index = pd.PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
>>> index.asfreq(freq='BMS')

we get on main

AttributeError: 'pandas._libs.tslibs.offsets.BusinessMonthBegin' object has no attribute '_period_dtype_code'

the correct behaviour would be raising an Error:

ValueError: BMS is not supported as period frequency

added to the definition of asfreq a check if string denoting frequency is supported as period frequency. If the index of a DataFrame is a PeriodIndex and the frequency is invalid period frequency a ValueError is raised.