Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use pandas to_offset to parse frequency string in date_range #9843

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions python/cudf/cudf/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import cupy as cp
import numpy as np
import pandas as pd
import pandas.tseries.offsets as pd_offset
from pandas.core.tools.datetimes import _unit_map

import cudf
Expand Down Expand Up @@ -458,6 +459,16 @@ class DateOffset:
"Y": "years",
}

_TICK_TO_UNITS = {
pd_offset.Day: "days",
pd_offset.Hour: "hours",
pd_offset.Minute: "minutes",
pd_offset.Second: "seconds",
pd_offset.Milli: "milliseconds",
pd_offset.Micro: "microseconds",
pd_offset.Nano: "nanoseconds",
}

_FREQSTR_REGEX = re.compile("([0-9]*)([a-zA-Z]+)")

def __init__(self, n=1, normalize=False, **kwds):
Expand Down Expand Up @@ -649,6 +660,10 @@ def _from_freqstr(cls: Type[_T], freqstr: str) -> _T:

return cls(**{cls._CODES_TO_UNITS[freq_part]: int(numeric_part)})

@classmethod
def _from_pandas_ticks(cls: Type[_T], tick: pd.tseries.offsets.Tick) -> _T:
return cls(**{cls._TICK_TO_UNITS[type(tick)]: tick.n})

def _maybe_as_fast_pandas_offset(self):
if (
len(self.kwds) == 1
Expand Down Expand Up @@ -814,23 +829,13 @@ def date_range(
if isinstance(freq, DateOffset):
offset = freq
elif isinstance(freq, str):
# Map pandas `offset alias` into cudf DateOffset `CODE`, only
# fixed-frequency, non-anchored offset aliases are supported.
mo = re.fullmatch(
rf'(-)*(\d*)({"|".join(_offset_alias_to_code.keys())})', freq
)
if mo is None:
offset = pd.tseries.frequencies.to_offset(freq)
if not isinstance(offset, pd.tseries.offsets.Tick):
raise ValueError(
f"Unrecognized or unsupported offset alias {freq}."
f"Unrecognized frequency string {freq}. cuDF does"
" not yet support month, quarter, year-anchored frequency."
isVoid marked this conversation as resolved.
Show resolved Hide resolved
)

sign, n, offset_alias = mo.groups()
code = _offset_alias_to_code[offset_alias]

freq = "".join([n, code])
offset = DateOffset._from_freqstr(freq)
if sign:
offset.kwds.update({s: -i for s, i in offset.kwds.items()})
offset = DateOffset._from_pandas_ticks(offset)
else:
raise TypeError("`freq` must be a `str` or cudf.DateOffset object.")

Expand Down
42 changes: 42 additions & 0 deletions python/cudf/cudf/tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,6 +1583,48 @@ def test_date_range_raise_overflow():
cudf.date_range(start=start, periods=periods, freq=freq)


@pytest.mark.parametrize(
"freqstr_unsupported",
[
"1M",
"2SM",
"3MS",
"4BM",
"5CBM",
"6SMS",
"7BMS",
"8CBMS",
"Q",
"2BQ",
"3BQS",
"10A",
"10Y",
"9BA",
"9BY",
"8AS",
"8YS",
"7BAS",
"7BYS",
"BH",
"B",
],
)
def test_date_range_raise_unsupported(freqstr_unsupported):
s, e = "2001-01-01", "2008-01-31"
pd.date_range(start=s, end=e, freq=freqstr_unsupported)
with pytest.raises(ValueError, match="does not yet support"):
cudf.date_range(start=s, end=e, freq=freqstr_unsupported)

# We also check that these values are unsupported when using lowercase
# characters. We exclude the value 3MS (every 3 month starts) because 3ms
# is a valid frequency for every 3 milliseconds.
if freqstr_unsupported != "3MS":
freqstr_unsupported = freqstr_unsupported.lower()
pd.date_range(start=s, end=e, freq=freqstr_unsupported)
with pytest.raises(ValueError, match="does not yet support"):
cudf.date_range(start=s, end=e, freq=freqstr_unsupported)


##################################################################
# End of Date Range Test #
##################################################################
Expand Down