user2333196
user2333196

Reputation: 5796

Return first non NaN value in python list

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

Answers (4)

Grant Shannon
Grant Shannon

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

Decon
Decon

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

Eric Leschinski
Eric Leschinski

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

user2555451
user2555451

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

Related Questions