return first non NaN value in python list

社会主义新天地 提交于 2021-02-08 19:57:54

问题


What would be the best way to return the first non nan value from this list?

testList = [nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]

edit:

nan is a float


回答1:


If you're doing it a lot, put it into a function to make it readable and easy:

import math

t = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]

def firstNonNan(listfloats):
  for item in listfloats:
    if math.isnan(item) == False:
      return item

firstNonNan(t)
5.5



回答2:


You can use next, a generator expression, and math.isnan:

>>> from math import isnan
>>> testList = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]
>>> next(x for x in testList if not isnan(x))
5.5
>>>



回答3:


It would be very easy if you were using NumPy:

array[numpy.isfinite(array)][0]

... returns the first finite (non-NaN and non-inf) value in the NumPy array 'array'.




回答4:


one line lambda below:

from math import isnan
lst = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]

lst
[nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]

first non nan value

lst[lst.index(next(filter(lambda x: not isnan(x), lst)))]
5.5

index of first non nan value

lst.index(next(filter(lambda x: not isnan(x), lst)))
2


来源:https://stackoverflow.com/questions/22129495/return-first-non-nan-value-in-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!