Simple question: I don't only want the value of the maximum but also the coordinates of it in an xarray DataArray. How to do that?
I can, of course, write my own simple reduce function, but I wonder if there is anything built-in in xarray?
Update:
xarray now has the idxmax
method for selecting the coords of the max values along one dimension:
In [8]: da = xr.DataArray(
...: np.random.rand(2,3),
...: dims=list('ab'),
...: coords=dict(a=list('xy'), b=list('ijk'))
...: )
In [14]: da
Out[14]:
<xarray.DataArray (a: 2, b: 3)>
array([[0.63059257, 0.00155463, 0.60763418],
[0.19680788, 0.43953352, 0.05602777]])
Coordinates:
* a (a) <U1 'x' 'y'
* b (b) <U1 'i' 'j' 'k'
In [13]: da.idxmax('a')
Out[13]:
<xarray.DataArray 'a' (b: 3)>
array(['x', 'y', 'x'], dtype=object)
Coordinates:
* b (b) <U1 'i' 'j' 'k'
The below answer is still relevant for the maximum over multiple dimensions, though.
You can use da.where()
to filter based on the max value:
In [17]: da = xr.DataArray(
np.random.rand(2,3),
dims=list('ab'),
coords=dict(a=list('xy'), b=list('ijk'))
)
In [18]: da.where(da==da.max(), drop=True).squeeze()
Out[18]:
<xarray.DataArray ()>
array(0.96213673)
Coordinates:
a <U1 'x'
b <U1 'j'
Edit: updated the example to show the indexes more clearly, now that xarray doesn't have default indexes