diff --git a/pandas/core/resample.py b/pandas/core/resample.py index b3e86b4360d74..39b2f4336730d 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -2784,7 +2784,13 @@ def asfreq( how = "E" if isinstance(freq, BaseOffset): - freq = freq_to_period_freqstr(freq.n, freq.name) + 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." + ) new_obj = obj.copy() new_obj.index = obj.index.asfreq(freq, how=how) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 60b222179ba12..703abbca91d64 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -970,6 +970,22 @@ def test_resample_t_l_deprecated(self): result = ser.resample("T").mean() tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "offset", + [ + offsets.MonthBegin(), + offsets.BYearBegin(2), + offsets.BusinessHour(2), + ], + ) + def test_asfreq_invalid_period_freq(self, offset, series_and_frame): + # GH#9586 + msg = f"Invalid offset: '{offset.base}' for converting time series " + + df = series_and_frame + with pytest.raises(ValueError, match=msg): + df.asfreq(freq=offset) + @pytest.mark.parametrize( "freq,freq_depr",