开发者

"isnotnan" functionality in numpy, can this be more pythonic?

开发者 https://www.devze.com 2022-12-30 10:04 出处:网络
I need a function that returns non-NaN values from an array. Currently I am doing it this way: >>> a = np.array([np.nan, 1, 2])

I need a function that returns non-NaN values from an array. Currently I am doing it this way:

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

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

>>>开发者_JAVA技巧; a[np.invert(np.isnan(a))]
array([ 1.,  2.])

Python: 2.6.4 numpy: 1.3.0

Please share if you know a better way, Thank you


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号