diff --git a/xarray/core/accessor_dt.py b/xarray/core/accessor_dt.py index 31ecd8709d0..071e814cf7a 100644 --- a/xarray/core/accessor_dt.py +++ b/xarray/core/accessor_dt.py @@ -1,7 +1,7 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, Any, cast import numpy as np import pandas as pd @@ -30,6 +30,10 @@ from xarray.core.types import CFCalendar +def _is_period_dtype(dtype: Any) -> bool: + return isinstance(dtype, pd.PeriodDtype) + + def _season_from_months(months): """Compute season (DJF, MAM, JJA, SON) from month ordinal.""" # TODO: Move "season" accessor upstream into pandas @@ -74,15 +78,25 @@ def _access_through_cftimeindex(values, name): return field_values.reshape(values.shape) -def _access_through_series(values, name): +def _datetime_series(values: Any) -> pd.Series: + if isinstance(values, pd.arrays.PeriodArray): + values = values.ravel() + elif not isinstance(values, pd.PeriodIndex): + values = duck_array_ops.ravel(values) + return pd.Series(values, copy=False) + + +def _access_through_series(values: Any, name: str) -> np.ndarray: """Access a datetime component via a pandas Series. Coerce an array of datetime-like values to a pandas Series and access the requested datetime component. """ - values_as_series = pd.Series(duck_array_ops.ravel(values), copy=False) + values_as_series = _datetime_series(values) if name == "season": months = values_as_series.dt.month.values + if isinstance(values.dtype, pd.PeriodDtype): + months = np.where(values_as_series.isna(), np.nan, months) field_values = _season_from_months(months) elif name == "total_seconds": field_values = values_as_series.dt.total_seconds().values @@ -103,9 +117,17 @@ def _access_through_series(values, name): field_values = np.array(field_values, dtype=np.int64) # isocalendar returns iso- year, week, and weekday -> reshape return field_values.T.reshape(3, *values.shape) + elif name == "days_in_year": + field_values = values_as_series.dt.is_leap_year.to_numpy(dtype=int) + 365 else: field_values = getattr(values_as_series.dt, name).values + if ( + isinstance(values.dtype, pd.PeriodDtype) + and np.issubdtype(field_values.dtype, np.integer) + and values_as_series.hasnans + ): + field_values = np.where(values_as_series.isna(), np.nan, field_values) return field_values.reshape(values.shape) @@ -130,7 +152,7 @@ def _get_date_field(values, name, dtype): Array-like of datetime fields accessed for each element in values """ - if is_np_datetime_like(values.dtype): + if isinstance(values.dtype, pd.PeriodDtype) or is_np_datetime_like(values.dtype): access_method = _access_through_series else: access_method = _access_through_cftimeindex @@ -163,8 +185,8 @@ def _round_through_series_or_index(values, name, freq): """ from xarray.coding.cftimeindex import CFTimeIndex - if is_np_datetime_like(values.dtype): - values_as_series = pd.Series(duck_array_ops.ravel(values), copy=False) + if isinstance(values.dtype, pd.PeriodDtype) or is_np_datetime_like(values.dtype): + values_as_series = _datetime_series(values) method = getattr(values_as_series.dt, name) else: values_as_cftimeindex = CFTimeIndex(duck_array_ops.ravel(values)) @@ -230,13 +252,13 @@ def _strftime_through_series(values, date_format: str): Coerce an array of datetime-like values to a pandas Series and apply string formatting. """ - values_as_series = pd.Series(duck_array_ops.ravel(values), copy=False) + values_as_series = _datetime_series(values) strs = values_as_series.dt.strftime(date_format) return strs.to_numpy().reshape(values.shape) def _strftime(values, date_format): - if is_np_datetime_like(values.dtype): + if isinstance(values.dtype, pd.PeriodDtype) or is_np_datetime_like(values.dtype): access_method = _strftime_through_series else: access_method = _strftime_through_cftimeindex @@ -390,7 +412,7 @@ def strftime(self, date_format: str) -> T_DataArray: """ obj_type = type(self._obj) - result = _strftime(self._obj.data, date_format) + result = _strftime(_index_or_data(self._obj), date_format) return obj_type( result, name="strftime", coords=self._obj.coords, dims=self._obj.dims @@ -405,10 +427,12 @@ def isocalendar(self) -> Dataset: """ from xarray.core.dataset import Dataset - if not is_np_datetime_like(self._obj.data.dtype): + if not _is_period_dtype(self._obj.dtype) and not is_np_datetime_like( + self._obj.dtype + ): raise AttributeError("'CFTimeIndex' object has no attribute 'isocalendar'") - values = _get_date_field(self._obj.data, "isocalendar", np.int64) + values = _get_date_field(_index_or_data(self._obj), "isocalendar", np.int64) obj_type = type(self._obj) data_vars = {} @@ -556,11 +580,15 @@ def calendar(self) -> CFCalendar: Only relevant for arrays of :py:class:`cftime.datetime` objects, returns "proleptic_gregorian" for arrays of :py:class:`numpy.datetime64` values. """ + if isinstance(self._obj.dtype, pd.PeriodDtype): + return "proleptic_gregorian" return infer_calendar_name(self._obj.data) @property def days_in_year(self) -> T_DataArray: """Each datetime as the year plus the fraction of the year elapsed.""" + if isinstance(self._obj.dtype, pd.PeriodDtype): + return self._date_field("days_in_year", np.int64) if self.calendar == "360_day": result = full_like(self.year, 360) else: @@ -666,14 +694,16 @@ def __new__(cls, obj: T_DataArray) -> Self: # we need to choose which parent (datetime or timedelta) is # appropriate. Since we're checking the dtypes anyway, we'll just # do all the validation here. - if not _contains_datetime_like_objects(obj.variable): + if not _is_period_dtype(obj.dtype) and not _contains_datetime_like_objects( + obj.variable + ): # We use an AttributeError here so that `obj.dt` raises an error that # `getattr` expects; https://github.com/pydata/xarray/issues/8718. It's a # bit unusual in a `__new__`, but that's the only case where we use this # class. raise AttributeError( "'.dt' accessor only available for " - "DataArray with datetime64 timedelta64 dtype or " + "DataArray with datetime64, timedelta64 or period dtype or " "for arrays containing cftime datetime " "objects." ) diff --git a/xarray/core/common.py b/xarray/core/common.py index 242681de42f..01a348d58cc 100644 --- a/xarray/core/common.py +++ b/xarray/core/common.py @@ -2050,11 +2050,15 @@ def get_chunksizes( def is_np_datetime_like(dtype: DTypeLike | None) -> bool: """Check if a dtype is a subclass of the numpy datetime types.""" + if isinstance(dtype, pd.api.extensions.ExtensionDtype): + return False return np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64) def is_np_timedelta_like(dtype: DTypeLike | None) -> bool: """Check whether dtype is of the timedelta64 dtype.""" + if isinstance(dtype, pd.api.extensions.ExtensionDtype): + return False return np.issubdtype(dtype, np.timedelta64) diff --git a/xarray/core/dataset_utils.py b/xarray/core/dataset_utils.py index 717ad73a175..d1d0c82ad81 100644 --- a/xarray/core/dataset_utils.py +++ b/xarray/core/dataset_utils.py @@ -81,7 +81,9 @@ def _get_virtual_variable( ref_name, var_name = split_key ref_var = variables[ref_name] - if _contains_datetime_like_objects(ref_var): + if isinstance(ref_var.dtype, pd.PeriodDtype) or _contains_datetime_like_objects( + ref_var + ): ref_var = DataArray(ref_var) data = getattr(ref_var.dt, var_name).data else: diff --git a/xarray/tests/test_accessor_dt.py b/xarray/tests/test_accessor_dt.py index 92dfa98655d..e6270797664 100644 --- a/xarray/tests/test_accessor_dt.py +++ b/xarray/tests/test_accessor_dt.py @@ -700,3 +700,60 @@ def test_decimal_year_all_nat() -> None: expected = xr.DataArray([np.nan, np.nan], dims="time") xr.testing.assert_equal(da.dt.decimal_year, expected) xr.testing.assert_equal(da[0].dt.decimal_year, expected[0]) + + +def test_period_accessor() -> None: + periods = pd.period_range("2000-01", "2000-12", freq="M") + da = xr.DataArray(periods.array, dims="time", coords={"time": periods}) + for values in (da, da.time): + for field in ( + "year", + "month", + "day", + "hour", + "minute", + "second", + "day_of_week", + "day_of_year", + "quarter", + "days_in_month", + "is_leap_year", + ): + assert_array_equal(getattr(values.dt, field), getattr(periods, field)) + assert_array_equal(values.dt.dayofweek, periods.day_of_week) + assert_array_equal(values.dt.weekday, periods.day_of_week) + assert_array_equal(values.dt.dayofyear, periods.day_of_year) + assert_array_equal(values.dt.daysinmonth, periods.days_in_month) + assert_array_equal(values.dt.strftime("%Y-%m"), periods.strftime("%Y-%m")) + assert values.dt.calendar == "proleptic_gregorian" + assert_array_equal(values.dt.days_in_year, np.full(12, 366)) + assert_array_equal( + values.dt.season, + ["DJF"] * 2 + ["MAM"] * 3 + ["JJA"] * 3 + ["SON"] * 3 + ["DJF"], + ) + for method in ("floor", "ceil", "round"): + with pytest.raises(AttributeError): + getattr(values.dt, method)("D") + with pytest.raises(AttributeError): + values.dt.isocalendar() + for field in ("date", "time"): + with pytest.raises(AttributeError): + getattr(values.dt, field) + + +@pytest.mark.parametrize("freq", ["D", "h", "Q"]) +def test_period_accessor_nat(freq: str) -> None: + periods = pd.PeriodIndex(["2000-01-01", pd.NaT], freq=freq) + da = xr.DataArray(periods.array, dims="time", coords={"time": periods}) + for values in (da, da.time): + for field in ("year", "month", "day", "days_in_month", "quarter"): + assert_array_equal( + getattr(values.dt, field), [getattr(periods[0], field), np.nan] + ) + assert_array_equal(values.dt.days_in_year, [366, np.nan]) + assert_array_equal(values.dt.season, ["MAM" if freq == "Q" else "DJF", "nan"]) + + +def test_non_period_extension_accessor() -> None: + with pytest.raises(AttributeError): + _ = xr.DataArray(pd.CategoricalIndex(["a"])).dt diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 69c683d3d89..e9a99509ec7 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -8843,3 +8843,11 @@ def test_transpose_error() -> None: ), ): ds.transpose(["y", "x"]) # type: ignore[arg-type] + + +def test_period_virtual_variables() -> None: + periods = pd.period_range("2000-01", "2000-12", freq="M") + ds = xr.Dataset({"a": ("time", np.arange(12))}, coords={"time": periods}) + np.testing.assert_array_equal(ds["time.month"], periods.month) + np.testing.assert_array_equal(ds.a["time.month"], periods.month) + np.testing.assert_array_equal(ds.a.groupby("time.month").sum(), ds.a)