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
8 changes: 8 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ Bug Fixes
~~~~~~~~~
- :py:meth:`Dataset.plot.quiver` now aligns hue values with the plotted vectors,
so missing hue values mask the correct arrows (:issue:`8928`).
- :py:meth:`DataArray.median` and :py:meth:`Dataset.median` no longer raise on
``datetime64`` data and return the median date, like :py:meth:`DataArray.mean`.
For ``timedelta64`` data, ``median`` now skips ``NaT`` by default like ``mean``
and no longer overflows for large values. ``mean`` of ``datetime64`` and
``timedelta64`` data is more precise and no longer overflows for large
``timedelta64`` values (:issue:`11964`, :pull:`11965`).
By `Swayam Prajapati <https://github.com/Swayam-27>`_ and
`Michael Niklas <https://github.com/headtr1ck>`_.


Documentation
Expand Down
80 changes: 57 additions & 23 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,7 @@ def func(values, axis=None, **kwargs):
std.numeric_only = True
var = _create_nan_agg_method("var")
var.numeric_only = True
median = _create_nan_agg_method("median", invariant_0d=True)
median.numeric_only = True
_median = _create_nan_agg_method("median", invariant_0d=True)
prod = _create_nan_agg_method("prod", invariant_0d=True)
prod.numeric_only = True
prod.available_min_count = True
Expand Down Expand Up @@ -774,31 +773,66 @@ def py_timedelta_to_float(array, datetime_unit):
return conversion_factor * array


def mean(array, axis=None, skipna=None, **kwargs):
"""Inhouse mean that can handle np.datetime64 or cftime.datetime dtypes."""
def _timelike_reduce(
func: Callable[..., Any],
array: Any,
axis: int | tuple[int, ...] | None = None,
skipna: bool | None = None,
**kwargs: Any,
) -> Any:
"""Reduce datetime64 or timedelta64 data with a float reduction ``func``.

numpy can't add datetimes, and adding timedeltas can overflow. Instead apply
``func`` to the float distances to the minimum along the reduced axes. Taking
the minimum exactly on the int64 ticks and per slice keeps the distances small,
so they stay exact as floats, and dask doesn't need a pass over the whole array.
The distances are computed as uint64, which holds the full datetime64 range.
"""
nat = isnull(array)
ticks = astype(array, np.int64)
offset = where(nat, np.iinfo(np.int64).max, ticks).min(axis=axis, keepdims=True)
# int64 subtraction wraps around, but the true distance fits in uint64
distances = astype(where(nat, offset, ticks) - offset, np.uint64)
distances = where(nat, np.nan, astype(distances, float))
result = func(distances, axis=axis, skipna=skipna, **kwargs)
# floats can round up to 2**64, which doesn't fit into uint64 anymore
limit = np.nextafter(2.0**64, 0)
result = where(result > limit, limit, result)
# the sum wraps around too, to the correct ticks of a valid datetime
offset = astype(offset.reshape(result.shape), np.uint64)
missing = isnull(result) # all-NaT slices or skipna=False
result = astype(offset + astype(where(missing, 0, result), np.uint64), np.int64)
return astype(where(missing, np.iinfo(np.int64).min, result), array.dtype)


def median(
array: Any,
axis: int | tuple[int, ...] | None = None,
skipna: bool | None = None,
**kwargs: Any,
) -> Any:
"""Inhouse median that can handle np.datetime64 and np.timedelta64 dtypes."""
array = asarray(array)
if dtypes.is_datetime_like(array.dtype):
return _timelike_reduce(_median, array, axis=axis, skipna=skipna, **kwargs)
return _median(array, axis=axis, skipna=skipna, **kwargs)


median.numeric_only = True # type: ignore[attr-defined]


def mean(
array: Any,
axis: int | tuple[int, ...] | None = None,
skipna: bool | None = None,
**kwargs: Any,
) -> Any:
"""Inhouse mean that can handle np.datetime64, np.timedelta64 or cftime.datetime dtypes."""
from xarray.core.common import _contains_cftime_datetimes

array = asarray(array)
if dtypes.is_datetime_like(array.dtype):
dmin = _datetime_nanreduce(array, min).astype("datetime64[Y]").astype(int)
dmax = _datetime_nanreduce(array, max).astype("datetime64[Y]").astype(int)
# midpoint computed without overflowing if both are NaT (i.e. int64 min)
offset = (
np.array(dmin + (dmax - dmin) // 2)
.astype("datetime64[Y]")
.astype(array.dtype)
)
# From version 2025.01.2 xarray uses np.datetime64[unit], where unit
# is one of "s", "ms", "us", "ns".
# To not have to worry about the resolution, we just convert the output
# to "timedelta64" (without unit) and let the dtype of offset take precedence.
# This is fully backwards compatible with datetime64[ns].
return (
_mean(
datetime_to_numeric(array, offset), axis=axis, skipna=skipna, **kwargs
).astype("timedelta64")
+ offset
)
return _timelike_reduce(_mean, array, axis=axis, skipna=skipna, **kwargs)
elif _contains_cftime_datetimes(array):
offset = min(array)
timedeltas = datetime_to_numeric(array, offset, datetime_unit="us")
Expand Down
101 changes: 101 additions & 0 deletions xarray/tests/test_duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,63 @@ def test_datetime_mean(use_dask: bool, time_unit: PDDatetimeUnitOptions) -> None
assert_equal(da[1].mean(skipna=False), expect_nat)


@pytest.mark.filterwarnings("ignore:All-NaN .* encountered:RuntimeWarning")
def test_datetime_median(use_dask: bool, time_unit: PDDatetimeUnitOptions) -> None:
dtype = f"M8[{time_unit}]"
values = np.array(
[
["2010-01-01", "NaT", "2010-01-04", "2010-01-02", "2010-01-07"],
["NaT", "NaT", "NaT", "NaT", "NaT"],
],
dtype=dtype,
)
da = DataArray(values, dims=["y", "time"])
if use_dask:
da = da.chunk({"y": 1})

# even number of valid values: the two middle ones are averaged
expect = DataArray(np.array(["2010-01-03", "NaT"], dtype=dtype), dims=["y"])
actual = da.median("time")
if use_dask:
assert actual.chunks is not None
assert_identical(actual, expect)
assert actual.dtype == np.dtype(dtype)
assert pd.Timestamp(actual.values[0]) == pd.Series(values[0]).median()

expect_nat = DataArray(np.array(["NaT", "NaT"], dtype=dtype), dims=["y"])
assert_identical(da.median("time", skipna=False), expect_nat)

# odd number of valid values
expect_odd = DataArray(np.array(["2010-01-02", "NaT"], dtype=dtype), dims=["y"])
assert_identical(da.isel(time=[0, 2, 3]).median("time"), expect_odd)


def test_datetime_median_0d() -> None:
da = DataArray(np.array("2010-01-01", dtype="M8[ns]"))
assert_identical(da.median(), da)


def test_datetime_median_exact() -> None:
# the result must be exact at nanosecond resolution
values = np.array(
[
"2000-06-15T00:00:00.000000001",
"2000-06-15T00:00:00.000000003",
"2000-06-15T00:00:00.000000007",
],
dtype="M8[ns]",
)
assert DataArray(values, dims="x").median().values == values[1]


def test_dataset_median_with_datetime_variable() -> None:
time = pd.date_range("2000-01-01", periods=4, freq="D")
ds = Dataset({"t": ("x", time), "v": ("x", np.arange(4.0))})
actual = ds.median()
assert actual["t"].values == np.datetime64("2000-01-02T12:00")
assert actual["v"].values == 1.5


@requires_cftime
def test_cftime_datetime_mean(use_dask):
times = date_range("2000", periods=4, use_cftime=True)
Expand Down Expand Up @@ -515,6 +572,50 @@ def test_mean_over_long_spanning_datetime64(use_dask) -> None:
assert_equal(result, expected)


@pytest.mark.parametrize("func", ["mean", "median"])
def test_datetime_reduction_far_apart_slices(use_dask: bool, func: str) -> None:
# the offset is taken per slice, so slices far apart from each other stay exact
values = np.array(
[
["2000-01-01T00:00:00.000000001", "2000-01-01T00:00:00.000000003"],
["2030-01-01T00:00:00.000000001", "2030-01-01T00:00:00.000000003"],
],
dtype="M8[ns]",
)
da = DataArray(values, dims=["x", "y"])
if use_dask:
da = da.chunk({"x": 1})
expected = DataArray(
np.array(
["2000-01-01T00:00:00.000000002", "2030-01-01T00:00:00.000000002"],
dtype="M8[ns]",
),
dims="x",
)
assert_identical(getattr(da, func)("y"), expected)


@pytest.mark.parametrize("func", ["mean", "median"])
def test_timedelta_mean_median(use_dask: bool, func: str) -> None:
values = np.array(
[
[1, 3, np.iinfo(np.int64).min], # NaT
# the sum of the two values overflows int64
[2**62, 2**62 + 2, np.iinfo(np.int64).min],
# the distance between the two values doesn't fit into int64
[-(2**62), 2**62, np.iinfo(np.int64).min],
]
).astype("m8[ns]")
da = DataArray(values, dims=["y", "x"])
if use_dask:
da = da.chunk({"y": 1})

expected = DataArray(np.array([2, 2**62 + 1, 0], dtype="m8[ns]"), dims="y")
assert_identical(getattr(da, func)("x"), expected)
expected_nat = DataArray(np.full(3, np.timedelta64("NaT", "ns")), dims="y")
assert_identical(getattr(da, func)("x", skipna=False), expected_nat)


@requires_cftime
@requires_dask
def test_mean_over_non_time_dim_of_dataset_with_dask_backed_cftime_data():
Expand Down
Loading