您的首要任务是可靠地识别np.nan 元素。因为它是一个唯一的浮点值,所以测试并非易事。 np.isnan 是最好的 numpy 工具。
要混合 boolean 和 float (np.nan),您必须使用 object dtype:
In [68]: arr = np.array([False, False, np.nan, np.nan, False],object)
In [69]: arr
Out[69]: array([False, False, nan, nan, False], dtype=object)
转换为浮点数会将 False 更改为 0(并将 True 更改为 1):
In [70]: arr.astype(float)
Out[70]: array([ 0., 0., nan, nan, 0.])
np.isnan 是对nan 的一个很好的测试,但它只适用于浮点数:
In [71]: np.isnan(arr)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-71-25d2f1dae78d> in <module>
----> 1 np.isnan(arr)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
In [72]: np.isnan(arr.astype(float))
Out[72]: array([False, False, True, True, False])
您可以使用辅助函数和列表推导来测试对象数组(或列表):
In [73]: def foo(x):
...: try:
...: return np.isnan(x)
...: except TypeError:
...: return x
...:
In [74]: [foo(x) for x in arr]
Out[74]: [False, False, True, True, False]
可靠地识别出nan 值后,您可以应用之前/之后的逻辑。我不确定列表或数组是否更容易(您的逻辑并不完全清楚)。