Skip to content

idxmax with multiple dimensions#10680

Open
gcaria wants to merge 15 commits into
pydata:mainfrom
gcaria:multiple-dims-idxmax
Open

idxmax with multiple dimensions#10680
gcaria wants to merge 15 commits into
pydata:mainfrom
gcaria:multiple-dims-idxmax

Conversation

@gcaria

@gcaria gcaria commented Aug 31, 2025

Copy link
Copy Markdown
Contributor

@max-sixty

Copy link
Copy Markdown
Collaborator

Looks good @gcaria !

Would it be possible to add a couple tests?

Comment thread xarray/computation/computation.py Outdated
res[_dim] = _res

if len(dims) == 1:
res = res[dims[0]]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should have some type stability here so

idmax(dim) -> array; idxmax((dim,)) -> tuple[array]; idxmax((dim0, dim1, ...)) -> tuple[array, ...]

@gcaria gcaria Sep 5, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have changed the code to match the behavior of DataArray.arg* which returns a dict for both idx*((dim,)) and idx*((dim0, dim1, ...))

Does that seem sensible?

Currently navigating the existing tests for arg* and multiple dims

@gcaria

gcaria commented Sep 7, 2025

Copy link
Copy Markdown
Contributor Author

While playing with the tests for arrays that contain nans, I found this, which doesn't seem to make sense (running on main):

import xarray as xr
import numpy as np

x = np.array([[ 2.,  1.,  2.,  0., -2., -4.,  2.],
       [-4., np.nan,  2., np.nan, -2., -4.,  2.],
       [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]])

ar = xr.DataArray(x,
                dims=["y", "x"],
                coords={
                "x": np.arange(x.shape[1]) * 4,
                "y": 1 - np.arange(x.shape[0])
},)

ar.idxmin('x', skipna=False) # ---> array([20,  4,  0])

Shouldn't the result be array([20, nan, nan]) (or error, see below)?
With the default skipna=True I do get array([20., 0., nan])

Interestingly ar.argmin('x') instead raises ValueError: All-NaN slice encountered, which I'd expect to show up also for idxmin.

@gcaria gcaria requested a review from dcherian September 30, 2025 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

idxmax with multiple dimensions

3 participants