问题
simple question: I don't only want the value of the maximum but also the coordinates of it in a xarray DataArray. How to do that?
I can of course write my own simple reduce funtion, but I wonder if there is anything built-in in xarray?
回答1:
You can use da.where() to filter based on the max 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
回答2:
An idxmax()
method would be very welcome in xarray, but nobody has gotten around to implementing it yet.
For now, you can find the coordinates of the maximum by combining argmax
and 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'
This is probably what .max()
should do in every case! Unfortunately we're not quite there yet.
The problem is that it doesn't yet generalize to the maximum over multiple dimensions in the way we would like:
>>> array.argmax() # what??
<xarray.DataArray ()>
array(2)
The problem is that it's automatically flattening, like np.argmax
. Instead, we probably want something like an array of tuples or a tuple of arrays, indicating the original integer coordinates for the maximum. Contributions for this would also be welcome -- see this issue for more details.
回答3:
You can also use stack :
Let's say data is a 3d variable with time, longitude, latitude and you want the coordinate of the maximum through time.
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)]
来源:https://stackoverflow.com/questions/40179593/how-to-get-the-coordinates-of-the-maximum-in-xarray