From cd9a43b4c993a8bef0c0d35e010bdaadeb1e9926 Mon Sep 17 00:00:00 2001 From: Natalia Mokeeva Date: Wed, 13 Dec 2023 19:52:04 +0100 Subject: [PATCH 1/2] raise ValueError if invalid period freq pass to asfreq --- pandas/core/resample.py | 8 +++++++- pandas/tests/resample/test_period_index.py | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index d54f6d31f6144..8864e7e8db93e 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..9663d35587c6e 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -970,6 +970,23 @@ 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 " + "with PeriodIndex." + + df = series_and_frame + with pytest.raises(ValueError, match=msg): + df.asfreq(freq=offset) + @pytest.mark.parametrize( "freq,freq_depr", From fc1ab4f45b510d2ba09dcbac0467ca2801167439 Mon Sep 17 00:00:00 2001 From: Natalia Mokeeva Date: Wed, 13 Dec 2023 20:44:14 +0100 Subject: [PATCH 2/2] fix pylint error --- pandas/tests/resample/test_period_index.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 9663d35587c6e..703abbca91d64 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -981,7 +981,6 @@ def test_resample_t_l_deprecated(self): def test_asfreq_invalid_period_freq(self, offset, series_and_frame): # GH#9586 msg = f"Invalid offset: '{offset.base}' for converting time series " - "with PeriodIndex." df = series_and_frame with pytest.raises(ValueError, match=msg):