6

I want to get the indices of an xarray data array where some condition is satisfied. An answer provided in a related thread (here) for how to find the location for the maximum did not work for me either. In my case, I want to find out the locations for other types of conditions too, not just maximum. Here is what I tried:

h=xr.DataArray(np.random.randn(3,4))
h.where(h==h.max(),drop=True).squeeze()

# This is the output I got:
<xarray.DataArray ()>
array(1.66065694)

This does not return the position as shown in the example I linked to, even though I am executing the same command. Am not sure why.

2 Answers2

6

I updated the linked example to show the indexes more clearly. Because xarray no longer adds default indexes, the previous example finds the max location but doesn't show the indexes. Copied below:

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'
Maximilian
  • 7,512
  • 3
  • 50
  • 63
0

I am not sure if I understood your question fully. Are you looking for the coordinate information? If so, try the command without .squeeze().

da.where(da==da.max(), drop=True)
Out[405]: 
<xarray.DataArray (a: 1, b: 1)>
array([[0.86409896]])
Coordinates:
  * a        (a) <U1 'y'
  * b        (b) <U1 'I'

Comparing to

da.where(da==da.max(), drop=True).squeeze()
Out[406]: 
<xarray.DataArray ()>
array(0.86409896)
Coordinates:
    a        <U1 'y'
    b        <U1 'i'