Reputation: 5796
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
Upvotes: 7
Views: 16040
Reputation: 5065
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
Upvotes: 1
Reputation: 91
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'.
Upvotes: 6
Reputation: 154063
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
Upvotes: 3
Reputation:
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
>>>
Upvotes: 11