在numpy数组中填充nan
当左非nan值和右非nan值匹配时,是否有一种直接的方法在numpy数组中填充nan值在numpy数组中填充nan,numpy,Numpy,当左非nan值和右非nan值匹配时,是否有一种直接的方法在numpy数组中填充nan值 例如,如果我有一个数组包含False、False、NaN、NaN、False,我希望NaN值也为False。如果左右值不匹配,我希望它保持NaN您的第一个任务是可靠地识别np.NaN元素。因为它是唯一的浮点值,所以测试不是trivailnp。isnan是最好的numpy工具 要混合布尔值和浮点值(np.nan),必须使用对象数据类型: In [68]: arr = np.array([False, False
例如,如果我有一个数组包含False、False、NaN、NaN、False,我希望NaN值也为False。如果左右值不匹配,我希望它保持NaN您的第一个任务是可靠地识别
np.NaN
元素。因为它是唯一的浮点值,所以测试不是trivail<代码>np。isnan是最好的numpy
工具
要混合布尔值和浮点值(np.nan
),必须使用对象数据类型:
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):
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])
可靠地识别了
nan
值后,您可以应用before/after逻辑。我不确定使用列表或数组是否更容易(您的逻辑并不完全清楚)。尝试使用numpy.isnan()函数False
是一个布尔值nan
us一个浮点数。如果您检查…。a=np.array([np.NaN,False,np.NaN,True])…将产生…。数组([nan,0.,nan,1.])…。显然你没有。你的实际阵列是什么?阵列的数据类型和形状是什么?结果呢?
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]