“ isnotnan”的功能在麻木,这可以更蟒蛇?

我需要一个从数组中返回非 NaN 值的函数:

>>> a = np.array([np.nan, 1, 2])
>>> a
array([ NaN,   1.,   2.])


>>> np.invert(np.isnan(a))
array([False,  True,  True], dtype=bool)


>>> a[np.invert(np.isnan(a))]
array([ 1.,  2.])

Python: 2.6.4 Numpy: 1.3.0

如果你知道更好的方法,请与我们分享, 谢谢你

131071 次浏览
a = a[~np.isnan(a)]

You are currently testing for anything that is not NaN and mtrw has the right way to do this. If you are interested in testing for finite numbers (is not NaN and is not INF) then you don't need an inversion and can use:

np.isfinite(a)

More pythonic and native, an easy read, and often when you want to avoid NaN you also want to avoid INF in my experience.

Just thought I'd toss that out there for folks.

I'm not sure whether this is more or less pythonic...

a = [i for i in a if i is not np.nan]

To get array([ 1., 2.]) from an array arr = np.array([np.nan, 1, 2]) You can do :

 arr[~np.isnan(arr)]

OR

arr[arr == arr]

(While : np.nan == np.nan is False)