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

Preserve base and loffset arguments in resample #7444

Merged
merged 18 commits into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
77 changes: 55 additions & 22 deletions xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@
import numpy as np
import pandas as pd

from xarray.coding import cftime_offsets
from xarray.core import dtypes, duck_array_ops, formatting, formatting_html, ops
from xarray.core.options import OPTIONS, _get_keep_attrs
from xarray.core.pycompat import is_duck_dask_array
from xarray.core.utils import Frozen, either_dict_or_kwargs, is_scalar
from xarray.core.utils import (
Frozen,
either_dict_or_kwargs,
emit_user_level_warning,
is_scalar,
)

try:
import cftime
Expand Down Expand Up @@ -928,8 +934,8 @@ def _resample(
"""
# TODO support non-string indexer after removing the old API.

from xarray.coding.cftimeindex import CFTimeIndex
from xarray.core.dataarray import DataArray
from xarray.core.groupby import TimeResampleGrouper
from xarray.core.resample import RESAMPLE_DIM

if keep_attrs is not None:
Expand Down Expand Up @@ -959,28 +965,36 @@ def _resample(
dim_name: Hashable = dim
dim_coord = self[dim]

if isinstance(self._indexes[dim_name].to_pandas_index(), CFTimeIndex):
from xarray.core.resample_cftime import CFTimeGrouper

grouper = CFTimeGrouper(
freq=freq,
closed=closed,
label=label,
base=base,
loffset=loffset,
origin=origin,
offset=offset,
if loffset is not None:
emit_user_level_warning(
"Following pandas, the `loffset` argument to resample will be deprecated in a "
"future version of xarray. Switch to using time offset arithmetic.",
FutureWarning,
)
else:
grouper = pd.Grouper(
freq=freq,
closed=closed,
label=label,
base=base,
offset=offset,
origin=origin,
loffset=loffset,

if base is None:
spencerkclark marked this conversation as resolved.
Show resolved Hide resolved
emit_user_level_warning(
"Following pandas, the `base` argument to resample will be deprecated in a "
"future version of xarray. Switch to using `origin` or `offset` instead.",
FutureWarning,
)

if base is not None and offset is not None:
raise ValueError("base and offset cannot be present at the same time")

if base is not None:
spencerkclark marked this conversation as resolved.
Show resolved Hide resolved
index = self._indexes[dim_name].to_pandas_index()
offset = _convert_base_to_offset(base, freq, index)

grouper = TimeResampleGrouper(
freq=freq,
closed=closed,
label=label,
origin=origin,
offset=offset,
loffset=loffset,
)

group = DataArray(
dim_coord, coords=dim_coord.coords, dims=dim_coord.dims, name=RESAMPLE_DIM
)
Expand Down Expand Up @@ -1799,3 +1813,22 @@ def _contains_datetime_like_objects(var) -> bool:
np.datetime64, np.timedelta64, or cftime.datetime)
"""
return is_np_datetime_like(var.dtype) or contains_cftime_datetimes(var)


def _convert_base_to_offset(base, freq, index):
"""Required until we officially deprecate the base argument to resample. This
translates a provided `base` argument to an `offset` argument, following logic
from pandas.
"""
from xarray.coding.cftimeindex import CFTimeIndex

if isinstance(index, pd.DatetimeIndex):
freq = pd.tseries.frequencies.to_offset(freq)
if isinstance(freq, pd.offsets.Tick):
return pd.Timedelta(base * freq.nanos // freq.n)
elif isinstance(index, CFTimeIndex):
freq = cftime_offsets.to_offset(freq)
if isinstance(freq, cftime_offsets.Tick):
return base * freq.as_timedelta() // freq.n
else:
raise ValueError("Can only resample using a DatetimeIndex or CFTimeIndex.")
59 changes: 46 additions & 13 deletions xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def _unique_and_monotonic(group: T_Group) -> bool:
return index.is_unique and index.is_monotonic_increasing


def _apply_loffset(grouper, result):
def _apply_loffset(loffset, result):
"""
(copied from pandas)
if loffset is set, offset the result index
Expand All @@ -258,17 +258,19 @@ def _apply_loffset(grouper, result):
result : Series or DataFrame
the result of resample
"""
# TODO: include some validation of the type of the loffset
# argument.
if isinstance(loffset, str):
loffset = pd.tseries.frequencies.to_offset(loffset)

needs_offset = (
isinstance(grouper.loffset, (pd.DateOffset, datetime.timedelta))
isinstance(loffset, (pd.DateOffset, datetime.timedelta))
and isinstance(result.index, pd.DatetimeIndex)
and len(result.index) > 0
)

if needs_offset:
result.index = result.index + grouper.loffset

grouper.loffset = None
result.index = result.index + loffset


class GroupBy(Generic[T_Xarray]):
Expand Down Expand Up @@ -530,14 +532,7 @@ def __repr__(self) -> str:
)

def _get_index_and_items(self, index, grouper):
from xarray.core.resample_cftime import CFTimeGrouper

s = pd.Series(np.arange(index.size), index)
if isinstance(grouper, CFTimeGrouper):
first_items = grouper.first_items(index)
else:
first_items = s.groupby(grouper).first()
_apply_loffset(grouper, first_items)
first_items = grouper.first_items(index)
full_index = first_items.index
if first_items.isnull().any():
first_items = first_items.dropna()
Expand Down Expand Up @@ -1365,3 +1360,41 @@ class DatasetGroupBy( # type: ignore[misc]
ImplementsDatasetReduce,
):
__slots__ = ()


class TimeResampleGrouper:
def __init__(self, freq, closed, label, origin, offset, loffset):
self.freq = freq
self.closed = closed
self.label = label
self.origin = origin
self.offset = offset
self.loffset = loffset

def first_items(self, index):
from xarray import CFTimeIndex
from xarray.core.resample_cftime import CFTimeGrouper

if isinstance(index, CFTimeIndex):
grouper = CFTimeGrouper(
freq=self.freq,
closed=self.closed,
label=self.label,
origin=self.origin,
offset=self.offset,
loffset=self.loffset,
)
return grouper.first_items(index)
else:
s = pd.Series(np.arange(index.size), index)
grouper = pd.Grouper(
freq=self.freq,
closed=self.closed,
label=self.label,
origin=self.origin,
offset=self.offset,
)

first_items = s.groupby(grouper).first()
_apply_loffset(self.loffset, first_items)
return first_items
8 changes: 0 additions & 8 deletions xarray/core/resample_cftime.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,13 @@ def __init__(
freq: str | BaseCFTimeOffset,
closed: SideOptions | None = None,
label: SideOptions | None = None,
base: int | None = None,
loffset: str | datetime.timedelta | BaseCFTimeOffset | None = None,
origin: str | CFTimeDatetime = "start_day",
offset: str | datetime.timedelta | None = None,
):
self.offset: datetime.timedelta | None
self.closed: SideOptions
self.label: SideOptions

if base is not None and offset is not None:
raise ValueError("base and offset cannot be provided at the same time")

self.freq = to_offset(freq)
self.loffset = loffset
self.origin = origin
Expand Down Expand Up @@ -122,9 +117,6 @@ def __init__(
else:
self.label = label

if base is not None and isinstance(self.freq, Tick):
offset = type(self.freq)(n=base % self.freq.n).as_timedelta()

if offset is not None:
try:
self.offset = _convert_offset_to_timedelta(offset)
Expand Down
2 changes: 2 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
assert_equal,
assert_identical,
create_test_data,
has_pandas_version_two,
requires_dask,
requires_flox,
requires_scipy,
Expand Down Expand Up @@ -1802,6 +1803,7 @@ def test_upsample_interpolate_dask(self, chunked_time):
# done here due to floating point arithmetic
assert_allclose(expected, actual, rtol=1e-16)

@pytest.mark.skipif(has_pandas_version_two, reason="requires pandas < 2.0.0")
def test_resample_base(self) -> None:
times = pd.date_range("2000-01-01T02:03:01", freq="6H", periods=10)
array = DataArray(np.arange(10), [("time", times)])
Expand Down