Skip to content

max, min and datetime mean/median raise on an empty dimension #11554

Description

@chiruu12

What happened?

max and min raise on an empty dimension instead of returning the fill value that mean, median and std return. On datetime64 the gap is wider: mean and median raise too, and median disagrees with timedelta64, which returns NaT from the same call.

#11549 covers quantile and describes the rest of the reductions as returning NaN. That is true for mean, median, std and var on numeric data, and not true for these.

What did you expect to happen?

NaN for numeric data and NaT for datetime and timedelta, which is what pandas returns and what the working reductions here already return.

Minimal Complete Verifiable Example

import numpy as np
import pandas as pd
import xarray as xr

empty = xr.DataArray(np.array([], dtype="f8"), dims="x")
empty.mean("x")     # nan
empty.max("x")      # ValueError: zero-size array to reduction operation fmax which has no identity
pd.Series([], dtype="f8").max()   # nan

dates = xr.DataArray(np.array([], dtype="M8[ns]"), dims="x")
dates.mean("x")     # ValueError: zero-size array to reduction operation fmin which has no identity
dates.median("x")   # UFuncTypeError: ufunc 'add' cannot use operands with types dtype('<M8[ns]')
pd.Series([], dtype="M8[ns]").max()   # NaT

xr.DataArray(np.array([], dtype="m8[ns]"), dims="x").median("x")   # NaT

Full matrix on 8ea7c88:

empty input mean median max / min
float64 nan nan ValueError
int64 nan nan ValueError
datetime64[ns] ValueError UFuncTypeError ValueError
timedelta64[ns] ValueError NaT ValueError

Two things stand out beyond the missing fill value. mean on datetime64 reports a failure in fmin, which is the internal offset subtraction showing through rather than anything the caller did. And median returns NaT for timedelta64 but raises for datetime64, so the two halves of the same path disagree.

sum and prod are not affected. They have identities and correctly return 0 and 1.

Only reducing over the empty dimension fails. xr.DataArray(np.zeros((0, 3)), dims=("x", "y")).max("y") returns shape (0,) as expected.

Environment

xarray 2026.7.1.dev43+ga48f3152c (main at 8ea7c88), numpy 2.2.6, pandas 2.3.3, python 3.12

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions