1

I have a dataarray that contains multidimensional coordinates for latitude and longitude (y,x). Xarray natively works with this data is great, and allows me to do something like da.max() and receive back a value. However, it seems that finding the coordinates associated with that max may not be as trivial (or I could be missing something).

Here is the structure of my dataarray:

xarray.DataArray 'Power' (y:1500, x:2500)
array([[nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]], dtype=float32)
Coordinates:
lon
(y, x)
float64
-113.1 -113.0 ... -52.98 -52.95
lat
(y, x)
float64
15.12 15.12 15.12 ... 51.36 51.36

Now, doing something like da.max() returns a value of array(3335.06591797). Trying da.argmax() also works and returns array(2365177). I think there could be a way to utilize this value to find where in the array, i.e. the coordinates, but I am not sure how to do that.

The third option is to try and utilize da.idxmax(), however that requires that the dataarray have common dimensions and coordinates, which I don't have in this case.

Maybe there is some sort of numpy way to do this as well, but I am unclear on a process to do it that way. Any thoughts on what to do here? Utilizing da.argmax() seems like the way to go, but am stuck.

Eli Turasky
  • 981
  • 2
  • 11
  • 28

1 Answers1

1

I check the documentation for argmax, it mentions the following for dim:

The dimensions over which to find the maximum. By default, finds maximum over all dimensions - for now returning an int for backward compatibility, but this is deprecated, in future will return a dict with indices for all dimensions; to return a dict with all dimensions now, pass ‘…’.

https://xarray.pydata.org/en/stable/generated/xarray.DataArray.argmax.html

So I think you were nearly there: just use an ellipsis: da.argmax(...).

To demonstrate:

import numpy as np
import xarray as xr

nrow = 2
ncol = 3
da = xr.DataArray(np.random.rand(nrow, ncol), {"x": range(ncol), "y": range(nrow)}, ["y", "x"])
da
<xarray.DataArray (y: 2, x: 3)>
array([[0.79480753, 0.06602363, 0.86688562],
       [0.37440161, 0.39527931, 0.31792832]])
Coordinates:
  * x        (x) int32 0 1 2
  * y        (y) int32 0 1

And da.argmax(...):

{'y': <xarray.DataArray ()>
 array(0, dtype=int64),
 'x': <xarray.DataArray ()>
 array(2, dtype=int64)}

There's also this earlier question: How to get the coordinates of the maximum in xarray? But it predates argmax.

Huite Bootsma
  • 451
  • 2
  • 6