其中包含numpy或xarray的函数返回包含nan值的结果

2024-04-26 17:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

假设我有一个小房间

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值除外,nan值应保留在结果中。你知道吗

我不能这样做努比。哪里'因为它删除了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的解决方案很简单,因为最新版本支持一个包含三个参数的函数。但是,NaN值仍保留在结果文件中。你知道吗


Tags: innumpybinabusrnanwherearray
2条回答

就像这样:

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))

相关问题 更多 >