Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
56 changes: 43 additions & 13 deletions xarray/core/accessor_dt.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)


Expand All @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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."
)
Expand Down
4 changes: 4 additions & 0 deletions xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
4 changes: 3 additions & 1 deletion xarray/core/dataset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
57 changes: 57 additions & 0 deletions xarray/tests/test_accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading