使用 numpy 或 xarray 的函数返回包括 nan 值的结果

Where function with numpy or xarray giving back the results including nan values

我在计算包含 0 和 1 但保留 nan 值的掩码时遇到了一个大问题。

假设我有一个 numpy-ndarray

ab = numpy.arange(0,10,0.5)

现在我模拟一个 nan 值:ab[3]=0。现在 'ab' 看起来像:

ab= array([ 0. ,  0.5,  1. ,  nan,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  
    5.,5.5,  6. ,  6.5,  7. ,  7.5,  8. ,  8.5,  9. ,  9.5])

现在我想将所有小于 5 的值屏蔽为“0”,将所有其他值屏蔽为“1”,除了 nan 值,它们应该保留在结果中。

我无法使用 'numpy.where' 执行此操作,因为它会删除 nan 值:

In [12]: numpy.where(a < 5, 1.0, 0.0)
/usr/bin/ipython3:1: RuntimeWarning: invalid value encountered in less
#!/usr/bin/env python3
Out[12]: array([ 1.,  1.,  1.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,
0.,  0., 0.,  0.,  0.,  0.,  0.,  0.,  0.])

我需要做什么才能保留 nan 值?

更新: xarray 的解决方案很简单,因为最新版本支持三参数 where-functionality。但是,NaN 值保留在结果文件中。

像那样:

import numpy as np

ab = np.arange(0,10,0.5)

ab[3] = np.nan

print(ab)

is_not_nan = np.logical_not(np.isnan(ab))
is_below_5 = ab < 5

is_not_nan_and_below_5 = np.logical_and(is_not_nan, is_below_5)

is_not_nan_and_not_below_5 = np.logical_and(is_not_nan, np.logical_not(is_below_5))

ab[is_not_nan_and_below_5] = 1.0
ab[is_not_nan_and_not_below_5] = 0.0

print(ab)

再用一个np.where

np.where(np.isnan(a), np.nan, numpy.where(a < 5, 1.0, 0.0))