Skip to content

Fix median() on datetime64 data - #11966

Closed
pinjun99 wants to merge 1 commit into
pydata:mainfrom
pinjun99:oss/11964
Closed

pinjun99 wants to merge 1 commit into
pydata:mainfrom
pinjun99:oss/11964

Conversation

@pinjun99

@pinjun99 pinjun99 commented Dec 1, 2026

Copy link
Copy Markdown

Description

median() on datetime64 data called np.median, which adds values and fails for datetime64. Because Dataset.median() reduces every variable, one datetime variable made the whole call fail.

For datetime64 (numpy dtype) inputs, the median now goes through the 0.5 quantile (nputils.nanquantile, or quantile when skipna=False). That keeps the input dtype and skips NaT by default, the same as mean() on datetimes. Other dtypes take the existing path.

Testing

  • New test_datetime_median (even and single-value cases, NaT with default / skipna=True / skipna=False) and TestDataset::test_median_datetime. Both fail on main with the numpy add error and pass with this change.
  • pytest xarray/tests/test_duck_array_ops.py xarray/tests/test_dataset.py xarray/tests/test_dataarray.py: 1744 passed, 753 skipped, 2 xfailed, 2 xpassed (numpy 2.5.5, pandas 3.1.2; dask was not installed locally, so the dask variants were skipped).
  • ruff check and ruff format pass.

Checklist

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: Codex (first draft of the fix and tests, which I then trimmed and changed so NaT is skipped by default).

@welcome

welcome Bot commented Dec 1, 2026

Copy link
Copy Markdown

Thank you for opening this pull request! It may take us a few days to respond here, so thank you for being patient.
If you have questions, some answers may be found in our contributing guidelines.

@github-actions github-actions Bot added the topic-arrays related to flexible array support label Dec 1, 2026
@headtr1ck

Copy link
Copy Markdown
Collaborator

Thanks for the PR! We'll go with #11965, which the issue author had announced in the issue. Going through nanquantile is also 3.5–10× slower than nanmedian on numpy arrays, and with dask median along the last axis fails with ValueError: `dtype` inference failed in `map_blocks` . So I'm closing this one.

@headtr1ck headtr1ck closed this Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic-arrays related to flexible array support

Projects

None yet

Development

Successfully merging this pull request may close these issues.

median() raises on datetime64 data and breaks Dataset.median()

2 participants