Skip to content

Commit 69f03a3

Browse files
authored
CLN: replace unnecessary freq_to_period_freqstr with PeriodDtype constructor (#56550)
* replace freq_to_period_freqstr() with PeriodDtype(freq)._freqstr in _shift_with_freq() * replace freq_to_period_freqstr with PeriodDtype()._freqstr except in frequencies.py, period.pyx * fix pre-commit errors * remove freq_to_period_freqstr from _maybe_coerce_freq and from tests * remove freq_to_period_freqstr from period.pyx * correct raise_on_incompatible * correct raise_on_incompatible again * replace warnings.simplefilter with warnings.filterwarnings in raise_on_incompatible * remove regex splitting from test_line_plot_datetime_frame * remove regex splitting from test_line_plot_period_mlt_frame
1 parent c864654 commit 69f03a3

File tree

13 files changed

+46
-52
lines changed

13 files changed

+46
-52
lines changed

pandas/_libs/tslibs/dtypes.pxd

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ cpdef int64_t periods_per_second(NPY_DATETIMEUNIT reso) except? -1
1111
cdef NPY_DATETIMEUNIT get_supported_reso(NPY_DATETIMEUNIT reso)
1212
cdef bint is_supported_unit(NPY_DATETIMEUNIT reso)
1313

14-
cpdef freq_to_period_freqstr(freq_n, freq_name)
1514
cdef dict c_OFFSET_TO_PERIOD_FREQSTR
1615
cdef dict c_OFFSET_DEPR_FREQSTR
1716
cdef dict c_REVERSE_OFFSET_DEPR_FREQSTR

pandas/_libs/tslibs/dtypes.pyi

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ OFFSET_TO_PERIOD_FREQSTR: dict[str, str]
77
def periods_per_day(reso: int = ...) -> int: ...
88
def periods_per_second(reso: int) -> int: ...
99
def abbrev_to_npy_unit(abbrev: str | None) -> int: ...
10-
def freq_to_period_freqstr(freq_n: int, freq_name: str) -> str: ...
1110

1211
class PeriodDtypeBase:
1312
_dtype_code: int # PeriodDtypeCode

pandas/_libs/tslibs/dtypes.pyx

-9
Original file line numberDiff line numberDiff line change
@@ -334,15 +334,6 @@ cdef dict c_REVERSE_OFFSET_DEPR_FREQSTR = {
334334
v: k for k, v in c_OFFSET_DEPR_FREQSTR.items()
335335
}
336336

337-
cpdef freq_to_period_freqstr(freq_n, freq_name):
338-
if freq_n == 1:
339-
freqstr = f"""{c_OFFSET_TO_PERIOD_FREQSTR.get(
340-
freq_name, freq_name)}"""
341-
else:
342-
freqstr = f"""{freq_n}{c_OFFSET_TO_PERIOD_FREQSTR.get(
343-
freq_name, freq_name)}"""
344-
return freqstr
345-
346337
# Map deprecated resolution abbreviations to correct resolution abbreviations
347338
cdef dict c_DEPR_ABBREVS = {
348339
"A": "Y",

pandas/_libs/tslibs/offsets.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -4698,7 +4698,7 @@ _lite_rule_alias = {
46984698
"ns": "ns",
46994699
}
47004700

4701-
_dont_uppercase = _dont_uppercase = {"h", "bh", "cbh", "MS", "ms", "s"}
4701+
_dont_uppercase = {"h", "bh", "cbh", "MS", "ms", "s"}
47024702

47034703

47044704
INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}"

pandas/_libs/tslibs/period.pyx

+12-11
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@ from libc.time cimport (
3838
tm,
3939
)
4040

41-
from pandas._libs.tslibs.dtypes cimport (
42-
c_OFFSET_TO_PERIOD_FREQSTR,
43-
freq_to_period_freqstr,
44-
)
41+
from pandas._libs.tslibs.dtypes cimport c_OFFSET_TO_PERIOD_FREQSTR
4542

4643
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
4744

@@ -97,9 +94,6 @@ from pandas._libs.tslibs.dtypes cimport (
9794
attrname_to_abbrevs,
9895
freq_group_code_to_npy_unit,
9996
)
100-
101-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
102-
10397
from pandas._libs.tslibs.parsing cimport quarter_to_myear
10498

10599
from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso
@@ -1554,7 +1548,7 @@ def extract_ordinals(ndarray values, freq) -> np.ndarray:
15541548
# if we don't raise here, we'll segfault later!
15551549
raise TypeError("extract_ordinals values must be object-dtype")
15561550

1557-
freqstr = freq_to_period_freqstr(freq.n, freq.name)
1551+
freqstr = PeriodDtypeBase(freq._period_dtype_code, freq.n)._freqstr
15581552

15591553
for i in range(n):
15601554
# Analogous to: p = values[i]
@@ -1722,8 +1716,15 @@ cdef class PeriodMixin:
17221716
condition = self.freq != other
17231717

17241718
if condition:
1725-
freqstr = freq_to_period_freqstr(self.freq.n, self.freq.name)
1726-
other_freqstr = freq_to_period_freqstr(other.n, other.name)
1719+
freqstr = PeriodDtypeBase(
1720+
self.freq._period_dtype_code, self.freq.n
1721+
)._freqstr
1722+
if hasattr(other, "_period_dtype_code"):
1723+
other_freqstr = PeriodDtypeBase(
1724+
other._period_dtype_code, other.n
1725+
)._freqstr
1726+
else:
1727+
other_freqstr = other.freqstr
17271728
msg = DIFFERENT_FREQ.format(
17281729
cls=type(self).__name__,
17291730
own_freq=freqstr,
@@ -2479,7 +2480,7 @@ cdef class _Period(PeriodMixin):
24792480
>>> pd.Period('2020-01', 'D').freqstr
24802481
'D'
24812482
"""
2482-
freqstr = freq_to_period_freqstr(self.freq.n, self.freq.name)
2483+
freqstr = PeriodDtypeBase(self.freq._period_dtype_code, self.freq.n)._freqstr
24832484
return freqstr
24842485

24852486
def __repr__(self) -> str:

pandas/core/arrays/period.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
from pandas._libs.tslibs.dtypes import (
3838
FreqGroup,
3939
PeriodDtypeBase,
40-
freq_to_period_freqstr,
4140
)
4241
from pandas._libs.tslibs.fields import isleapyear_arr
4342
from pandas._libs.tslibs.offsets import (
@@ -325,7 +324,7 @@ def _from_datetime64(cls, data, freq, tz=None) -> Self:
325324
PeriodArray[freq]
326325
"""
327326
if isinstance(freq, BaseOffset):
328-
freq = freq_to_period_freqstr(freq.n, freq.name)
327+
freq = PeriodDtype(freq)._freqstr
329328
data, freq = dt64arr_to_periodarr(data, freq, tz)
330329
dtype = PeriodDtype(freq)
331330
return cls(data, dtype=dtype)
@@ -399,7 +398,7 @@ def freq(self) -> BaseOffset:
399398

400399
@property
401400
def freqstr(self) -> str:
402-
return freq_to_period_freqstr(self.freq.n, self.freq.name)
401+
return PeriodDtype(self.freq)._freqstr
403402

404403
def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
405404
if dtype == "i8":
@@ -1002,13 +1001,17 @@ def raise_on_incompatible(left, right) -> IncompatibleFrequency:
10021001
if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None:
10031002
other_freq = None
10041003
elif isinstance(right, BaseOffset):
1005-
other_freq = freq_to_period_freqstr(right.n, right.name)
1004+
with warnings.catch_warnings():
1005+
warnings.filterwarnings(
1006+
"ignore", r"PeriodDtype\[B\] is deprecated", category=FutureWarning
1007+
)
1008+
other_freq = PeriodDtype(right)._freqstr
10061009
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period)):
10071010
other_freq = right.freqstr
10081011
else:
10091012
other_freq = delta_to_tick(Timedelta(right)).freqstr
10101013

1011-
own_freq = freq_to_period_freqstr(left.freq.n, left.freq.name)
1014+
own_freq = PeriodDtype(left.freq)._freqstr
10121015
msg = DIFFERENT_FREQ.format(
10131016
cls=type(left).__name__, own_freq=own_freq, other_freq=other_freq
10141017
)

pandas/core/generic.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
Timestamp,
3535
to_offset,
3636
)
37-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
3837
from pandas._typing import (
3938
AlignJoin,
4039
AnyArrayLike,
@@ -123,6 +122,7 @@
123122
from pandas.core.dtypes.dtypes import (
124123
DatetimeTZDtype,
125124
ExtensionDtype,
125+
PeriodDtype,
126126
)
127127
from pandas.core.dtypes.generic import (
128128
ABCDataFrame,
@@ -10358,9 +10358,9 @@ def _shift_with_freq(self, periods: int, axis: int, freq) -> Self:
1035810358
if freq != orig_freq:
1035910359
assert orig_freq is not None # for mypy
1036010360
raise ValueError(
10361-
f"Given freq {freq_to_period_freqstr(freq.n, freq.name)} "
10361+
f"Given freq {PeriodDtype(freq)._freqstr} "
1036210362
f"does not match PeriodIndex freq "
10363-
f"{freq_to_period_freqstr(orig_freq.n, orig_freq.name)}"
10363+
f"{PeriodDtype(orig_freq)._freqstr}"
1036410364
)
1036510365
new_ax: Index = index.shift(periods)
1036610366
else:

pandas/core/indexes/datetimelike.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
parsing,
2929
to_offset,
3030
)
31-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
3231
from pandas.compat.numpy import function as nv
3332
from pandas.errors import (
3433
InvalidIndexError,
@@ -45,7 +44,10 @@
4544
is_list_like,
4645
)
4746
from pandas.core.dtypes.concat import concat_compat
48-
from pandas.core.dtypes.dtypes import CategoricalDtype
47+
from pandas.core.dtypes.dtypes import (
48+
CategoricalDtype,
49+
PeriodDtype,
50+
)
4951

5052
from pandas.core.arrays import (
5153
DatetimeArray,
@@ -139,7 +141,7 @@ def freqstr(self) -> str:
139141
if self._data.freqstr is not None and isinstance(
140142
self._data, (PeriodArray, PeriodIndex)
141143
):
142-
freq = freq_to_period_freqstr(self._data.freq.n, self._data.freq.name)
144+
freq = PeriodDtype(self._data.freq)._freqstr
143145
return freq
144146
else:
145147
return self._data.freqstr # type: ignore[return-value]

pandas/core/resample.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
Timestamp,
2626
to_offset,
2727
)
28-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
2928
from pandas._typing import NDFrameT
3029
from pandas.errors import AbstractMethodError
3130
from pandas.util._decorators import (
@@ -38,7 +37,10 @@
3837
rewrite_warning,
3938
)
4039

41-
from pandas.core.dtypes.dtypes import ArrowDtype
40+
from pandas.core.dtypes.dtypes import (
41+
ArrowDtype,
42+
PeriodDtype,
43+
)
4244
from pandas.core.dtypes.generic import (
4345
ABCDataFrame,
4446
ABCSeries,
@@ -2650,7 +2652,7 @@ def asfreq(
26502652

26512653
if isinstance(freq, BaseOffset):
26522654
if hasattr(freq, "_period_dtype_code"):
2653-
freq = freq_to_period_freqstr(freq.n, freq.name)
2655+
freq = PeriodDtype(freq)._freqstr
26542656

26552657
new_obj = obj.copy()
26562658
new_obj.index = obj.index.asfreq(freq, how=how)

pandas/io/json/_table_schema.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from pandas._libs import lib
1616
from pandas._libs.json import ujson_loads
1717
from pandas._libs.tslibs import timezones
18-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
1918
from pandas.util._exceptions import find_stack_level
2019

2120
from pandas.core.dtypes.base import _registry as registry
@@ -212,8 +211,7 @@ def convert_json_field_to_pandas_type(field) -> str | CategoricalDtype:
212211
elif field.get("freq"):
213212
# GH#9586 rename frequency M to ME for offsets
214213
offset = to_offset(field["freq"])
215-
freq_n, freq_name = offset.n, offset.name
216-
freq = freq_to_period_freqstr(freq_n, freq_name)
214+
freq = PeriodDtype(offset)._freqstr
217215
# GH#47747 using datetime over period to minimize the change surface
218216
return f"period[{freq}]"
219217
else:

pandas/tests/arrays/test_datetimelike.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
OutOfBoundsDatetime,
1212
Timestamp,
1313
)
14-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
14+
from pandas._libs.tslibs import to_offset
15+
16+
from pandas.core.dtypes.dtypes import PeriodDtype
1517

1618
import pandas as pd
1719
from pandas import (
@@ -51,7 +53,7 @@ def period_index(freqstr):
5153
warnings.filterwarnings(
5254
"ignore", message="Period with BDay freq", category=FutureWarning
5355
)
54-
freqstr = freq_to_period_freqstr(1, freqstr)
56+
freqstr = PeriodDtype(to_offset(freqstr))._freqstr
5557
pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr)
5658
return pi
5759

@@ -761,7 +763,7 @@ def test_to_period(self, datetime_index, freqstr):
761763
dti = datetime_index
762764
arr = dti._data
763765

764-
freqstr = freq_to_period_freqstr(1, freqstr)
766+
freqstr = PeriodDtype(to_offset(freqstr))._freqstr
765767
expected = dti.to_period(freq=freqstr)
766768
result = arr.to_period(freq=freqstr)
767769
assert isinstance(result, PeriodArray)

pandas/tests/plotting/test_datetimelike.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
BaseOffset,
1515
to_offset,
1616
)
17-
from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
17+
18+
from pandas.core.dtypes.dtypes import PeriodDtype
1819

1920
from pandas import (
2021
DataFrame,
@@ -239,8 +240,7 @@ def test_line_plot_period_mlt_frame(self, frqncy):
239240
index=idx,
240241
columns=["A", "B", "C"],
241242
)
242-
freq = freq_to_period_freqstr(1, df.index.freq.rule_code)
243-
freq = df.index.asfreq(freq).freq
243+
freq = df.index.freq.rule_code
244244
_check_plot_works(df.plot, freq)
245245

246246
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
@@ -254,7 +254,7 @@ def test_line_plot_datetime_frame(self, freq):
254254
index=idx,
255255
columns=["A", "B", "C"],
256256
)
257-
freq = freq_to_period_freqstr(1, df.index.freq.rule_code)
257+
freq = PeriodDtype(df.index.freq)._freqstr
258258
freq = df.index.to_period(freq).freq
259259
_check_plot_works(df.plot, freq)
260260

pandas/tseries/frequencies.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,7 @@
1919
MONTHS,
2020
int_to_weekday,
2121
)
22-
from pandas._libs.tslibs.dtypes import (
23-
OFFSET_TO_PERIOD_FREQSTR,
24-
freq_to_period_freqstr,
25-
)
22+
from pandas._libs.tslibs.dtypes import OFFSET_TO_PERIOD_FREQSTR
2623
from pandas._libs.tslibs.fields import (
2724
build_field_sarray,
2825
month_position_check,
@@ -559,7 +556,7 @@ def _maybe_coerce_freq(code) -> str:
559556
"""
560557
assert code is not None
561558
if isinstance(code, DateOffset):
562-
code = freq_to_period_freqstr(1, code.name)
559+
code = PeriodDtype(to_offset(code.name))._freqstr
563560
if code in {"h", "min", "s", "ms", "us", "ns"}:
564561
return code
565562
else:

0 commit comments

Comments
 (0)