Skip to content

Commit df913e7

Browse files
authored
ENH: Raise TypeError when converting DatetimeIndex to PeriodIndex with invalid period frequency (#56243)
1 parent e0f3a18 commit df913e7

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v2.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ Other enhancements
226226
- Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`)
227227
- DataFrame.apply now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`)
228228
- Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`)
229+
- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as "BMS" (:issue:`56243`)
229230
- Improved error message when constructing :class:`Period` with invalid offsets such as "QS" (:issue:`55785`)
230231

231232
.. ---------------------------------------------------------------------------

pandas/core/arrays/period.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1174,7 +1174,12 @@ def dt64arr_to_periodarr(
11741174

11751175
reso = get_unit_from_dtype(data.dtype)
11761176
freq = Period._maybe_convert_freq(freq)
1177-
base = freq._period_dtype_code
1177+
try:
1178+
base = freq._period_dtype_code
1179+
except (AttributeError, TypeError):
1180+
# AttributeError: _period_dtype_code might not exist
1181+
# TypeError: _period_dtype_code might intentionally raise
1182+
raise TypeError(f"{freq.name} is not supported as period frequency")
11781183
return c_dt64arr_to_periodarr(data.view("i8"), base, tz, reso=reso), freq
11791184

11801185

pandas/tests/indexes/datetimes/methods/test_to_period.py

+8
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,11 @@ def test_to_period_nofreq(self):
230230
idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"])
231231
assert idx.freqstr is None
232232
tm.assert_index_equal(idx.to_period(), expected)
233+
234+
@pytest.mark.parametrize("freq", ["2BMS", "1SME-15"])
235+
def test_to_period_offsets_not_supported(self, freq):
236+
# GH#56243
237+
msg = f"{freq[1:]} is not supported as period frequency"
238+
ts = date_range("1/1/2012", periods=4, freq=freq)
239+
with pytest.raises(TypeError, match=msg):
240+
ts.to_period()

0 commit comments

Comments
 (0)