How to get maximum coordinates in xarray?

simple question: I not only want the maximum value, but also its coordinates in xarray DataArray. How to do it?

I can, of course, write my own simple funtion effect, but I wonder if there is anything built into xarray?

+10
source share
3 answers

You can use da.where()to filter by maximum value:

In [15]: da = xr.DataArray(np.random.rand(2,3,4))

In [16]: da.where(da==da.max(), drop=True).squeeze()
Out[16]: 
<xarray.DataArray (dim_0: 1, dim_1: 1, dim_2: 1)>
array([[[ 0.91077406]]])
Coordinates:
  * dim_0    (dim_0) int64 0
  * dim_1    (dim_1) int64 2
  * dim_2    (dim_2) int64 3
+18
source

idxmax()would be very desirable in xarray, but so far no one bothered to implement it.

At the moment, you can find the coordinates of the maximum by combining argmaxand isel:

>>> array = xarray.DataArray(
...    [[1, 2, 3], [3, 2, 1]],
...    dims=['x', 'y'],
...    coords={'x': [1, 2], 'y': ['a', 'b', 'c']})

>>> array
<xarray.DataArray (x: 2, y: 3)>
array([[1, 2, 3],
       [3, 2, 1]])
Coordinates:
  * x        (x) int64 1 2
  * y        (y) <U1 'a' 'b' 'c'

>>> array.isel(y=array.argmax('y'))
<xarray.DataArray (x: 2)>
array([3, 3])
Coordinates:
  * x        (x) int64 1 2
    y        (x) <U1 'c' 'a'

, , , .max() ! , .

, , :

>>> array.argmax()  # what??
<xarray.DataArray ()>
array(2)

, , np.argmax. , , - , . - . .

+3

:

, , , , .

stackdata = data.stack(z=('lon', 'lat'))
maxi = stackdata.argmax(axis=1)
maxipos = stackdata['z'][maxi]
lonmax = [maxipos.values[itr][0] for itr in range(ntime)]
latmax = [maxipos.values[itr][1] for itr in range(ntime)]
0

Source: https://habr.com/ru/post/1658463/


All Articles