Skip to content

use mean of min/max years as offset in calculation of datetime64 mean #10035

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

Merged
merged 4 commits into from
Feb 7, 2025
Merged
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
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ Bug fixes
"nanoseconds" were chosen by default, which are optimal for
nanosecond-resolution times, but not for times with coarser resolution. By
`Spencer Clark <https://github.com/spencerkclark>`_ (:pull:`10017`).
- Use mean of min/max years as offset in calculation of datetime64 mean
(:issue:`10019`, :pull:`10035`).
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_.


Documentation
Expand Down
17 changes: 12 additions & 5 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@
xp = get_array_namespace(data)
if xp == np:
# numpy currently doesn't have a astype:
return data.astype(dtype, **kwargs)

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / macos-latest py3.10

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / macos-latest py3.10

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / macos-latest py3.12

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / macos-latest py3.12

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.12

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.12

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / windows-latest py3.10

invalid value encountered in cast

Check warning on line 232 in xarray/core/duck_array_ops.py

View workflow job for this annotation

GitHub Actions / windows-latest py3.10

invalid value encountered in cast
return xp.astype(data, dtype, **kwargs)
return data.astype(dtype, **kwargs)

Expand Down Expand Up @@ -550,7 +550,11 @@


def _datetime_nanmin(array):
"""nanmin() function for datetime64.
return _datetime_nanreduce(array, min)


def _datetime_nanreduce(array, func):
"""nanreduce() function for datetime64.

Caveats that this function deals with:

Expand All @@ -562,7 +566,7 @@
assert dtypes.is_datetime_like(dtype)
# (NaT).astype(float) does not produce NaN...
array = where(pandas_isnull(array), np.nan, array.astype(float))
array = min(array, skipna=True)
array = func(array, skipna=True)
if isinstance(array, float):
array = np.array(array)
# ...but (NaN).astype("M8") does produce NaT
Expand Down Expand Up @@ -597,7 +601,7 @@
# Set offset to minimum if not given
if offset is None:
if dtypes.is_datetime_like(array.dtype):
offset = _datetime_nanmin(array)
offset = _datetime_nanreduce(array, min)
else:
offset = min(array)

Expand Down Expand Up @@ -717,8 +721,11 @@

array = asarray(array)
if dtypes.is_datetime_like(array.dtype):
offset = _datetime_nanmin(array)

dmin = _datetime_nanreduce(array, min).astype("datetime64[Y]").astype(int)
dmax = _datetime_nanreduce(array, max).astype("datetime64[Y]").astype(int)
offset = (
np.array((dmin + dmax) // 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
Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,19 @@ def test_cftime_datetime_mean(dask):
assert_equal(result, expected)


@pytest.mark.parametrize("dask", [False, True])
def test_mean_over_long_spanning_datetime64(dask) -> None:
if dask and not has_dask:
pytest.skip("requires dask")
array = np.array(["1678-01-01", "NaT", "2260-01-01"], dtype="datetime64[ns]")
da = DataArray(array, dims=["time"])
if dask:
da = da.chunk({"time": 2})
expected = DataArray(np.array("1969-01-01", dtype="datetime64[ns]"))
result = da.mean()
assert_equal(result, expected)


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