1

I have a multidimensional xarray like:

testarray = xr.DataArray([[1,-2,3],[4,5,-6]])

and i want to get the indices for a specific condition, eg. where testarray is smaller then 0. So the expected result should be an array like:

result = [[1,2],[0,1]]

Or any other format that let me get these indices for further calculations. Can't imagine, that there is no option within xarray for such an elementary problem, but i can't find it. Things like

testarray.where(testarray<0)

do some very ???suspicious??? stuff. Whats the use of an array thats the same but with nan's where conditions not met???

Thanks alot for your help :)

2
  • did you looked here ? xarray.pydata.org/en/stable/generated/… Commented Sep 24, 2020 at 19:51
  • Yes, but i think i'm to stupid to get it work ;) There is well explaine how to change values that match to a specific condition. But i have no idea how to get the indices of the values that match a specific condition. Commented Sep 24, 2020 at 21:09

1 Answer 1

2

To get the indices, you could use np.argwhere:

In [3]: da= xr.DataArray([[1,-2,3],[4,5,-6]])

In [4]: da
Out[4]:
<xarray.DataArray (dim_0: 2, dim_1: 3)>
array([[ 1, -2,  3],
       [ 4,  5, -6]])
Dimensions without coordinates: dim_0, dim_1


In [14]: da.where(da<0,0)
Out[14]:
<xarray.DataArray (dim_0: 2, dim_1: 3)>
array([[ 0, -2,  0],
       [ 0,  0, -6]])
Dimensions without coordinates: dim_0, dim_1

# Note you'd need to handle the case of a 0 value here

In [13]: np.argwhere(da.where(da<0,0).values)
Out[13]:
array([[0, 1],
       [1, 2]])

I agree this would be useful function to have natively in xarray; I'm not sure of the best way of doing it natively at the moment. Open to ideas!

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for that solution. Well, as far as i have figured out combining numpy with xarray is simple. numpy.where does exactly what i want, but it is a very fragile and often easy error-prone, because it always depends on the type and mixing types liky run into broadcasting errors driving me as a beginner crazy. And in mor complex functions you tend to get those crazy lines like xarray(np.array(xarray(np.arrray....))) .. .. well, not that nice to handle sometimes ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.