简体   繁体   English

Python xarray 索引返回

[英]Python xarray index return

I have a multidimensional xarray like:我有一个多维 xarray 像:

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:其中 testarray 小于 0。所以预期的结果应该是一个像这样的数组:

result = [[1,2],[0,1]]结果 = [[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.无法想象,对于这样一个基本问题,xarray 中没有选项,但我找不到它。 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???什么是相同的数组的用途,但 nan 的 where 条件不满足???

Thanks alot for your help :)非常感谢你的帮助 :)

To get the indices, you could use np.argwhere :要获取索引,您可以使用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;我同意这将是 xarray 中原生的有用功能; I'm not sure of the best way of doing it natively at the moment.我不确定目前在本地进行的最佳方式。 Open to ideas!开放的想法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM