简体   繁体   中英

Python Dataarray conditional .where() keep nan Values but turn negative values to 0

I have this problem for hours now, I can not seem to resolve it. I have an xarray dataarray with nan values (numpy.float32), positive, and negative values (numpy.float32). Now I want to turn the negative values to 0 - ONLY THIS. But even such a seemingly easy task is impossible for me to solve. For example, this what I have been working with. (xarray.core.dataarray.DataArray) type.

The preceding code is:

path = r'D:\....'
dObj = xr.open_dataset(path)
JJA = dObj ['cba'].sel(time=dObj.time.values)

The Object then looks like this: ( I am terribly sorry that I can not provide the.nc File since it is 200mb and I have no idea how to slice it accordingly)

在此处输入图像描述

JJA

在此处输入图像描述

My solution was:

JJA = JJA.where(JJA>0,0)

But somehow this turns negative AND nan values into 0, no idea why. Then I tried different approaches and made the conditional a bit more complicated.

JJA = JJA.where((np.isnan(JJA)==False)&(JJA > 0),0)

But nothing, it still turns into:

JJA

在此处输入图像描述

As stated in the xarray docs , a line like JJA = JJA.where(JJA>0,0) will return a DataArray with the values preserved which meet cond (ie, JJA>0 ) and will return 0 for everything else . So that's why it changes everything that doesn't meet that condition (including NaN, zero, and negative values) to 0.

The reason your more complex mask doesnt work is you are using AND instead of OR. If you want to set only the negative values to zero and leave NaNs alone, you could do something like: JJA = JJA.where((JJA > 0) | JJA.isnull(), 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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