[英]Set values in xarray DataArray to NaN if all values across a dimension are zero
I have an xarray like this:我有一个这样的xarray:
import xarray as xr
da1 = xr.DataArray([[0, 1, 5, 5], [1, 2, 2, 0], [9, 3, 2, 0]], dims=['x', 'y'])
da2 = xr.DataArray([[0, 2, 9, 3], [0, 0, 7, 0], [0, 2, 6, 0]], dims=['x', 'y'])
da3 = xr.DataArray([[0, 7, 2, 0], [7, 2, 6, 0], [0, 6, 1, 0]], dims=['x', 'y'])
combined = xr.concat([da1, da2, da3], 'band')
It looks like this:它看起来像这样:
array([[[0, 1, 5, 5],
[1, 2, 2, 0],
[9, 3, 2, 0]],
[[0, 2, 9, 3],
[0, 0, 7, 0],
[0, 2, 6, 0]],
[[0, 7, 2, 0],
[7, 2, 6, 0],
[0, 6, 1, 0]]])
with three dimensions: band
, x
and y
.具有三个维度: band
、 x
和y
。
I want to set the values in this array to NaN in the situations where all the values across the band
dimension are zero.在band
维度上的所有值都为零的情况下,我想将此数组中的值设置为 NaN。 For example, the values at combined.isel(x=0, y=0)
should be set to NaN, as all those values are zero, but the values at combined.isel(x=1, y=1)
should not be, as only one of the values is zero.例如, combined.isel(x=0, y=0)
处的值应设置为 NaN,因为所有这些值均为零,但combined.isel(x=1, y=1)
处的值不应为,因为只有一个值为零。
How can I do this?我怎样才能做到这一点?
I've tried using:我试过使用:
combined.where(combined != 0)
but this sets all values that are zero to NaN, which doesn't do what I want.但这会将所有为零的值设置为 NaN,这不符合我的要求。
I then tried something like:然后我尝试了类似的东西:
combined.where((combined.isel(band=0) != 0) & (combined.isel(band=1) != 0) & (combined.isel(band=2) != 0))
but the 'and' bit doesn't seem to work properly and it gives a strange (and incorrect) result.但是“和”位似乎无法正常工作,并且给出了奇怪(且不正确)的结果。
Update: As an extension, I would like to be able to do the same thing but for very small values, rather than zeros.更新:作为扩展,我希望能够做同样的事情,但值非常小,而不是零。 For example, setting all values across the band
dimension to NaN if all values across that dimension are < 0.01.例如,如果跨维度的所有值都 < 0.01,则将跨band
的所有值设置为 NaN。 Is there an easy way to do this?是否有捷径可寻?
Any advice very much appreciated非常感谢任何建议
You can do that with:你可以这样做:
combined.where(combined.any(dim = 'band'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.