在Python列表中返回第一个非NaN值

7
这个列表中返回第一个非NaN值的最佳方法是什么?
testList = [nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]

编辑:

nan是一个浮点数

4个回答

11

您可以使用next生成器表达式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
>>>

next(x for x in testList if x == x) 也可以工作,并且可能会更快,因为它避免了很多函数查找(虽然相当难读懂)。 - Bakuriu

5
如果您使用NumPy,那么这将非常容易:
array[numpy.isfinite(array)][0]

...返回NumPy数组“array”中第一个有限值(非NaN和非inf)。


非常干净,可能比手动循环更快。 - user2647513
我肯定对这个方法有所不理解,但它似乎仍然是最简单的方法,因此我通过创建True和False值的数组并计算我需要的数量来进行管理:list(np.isfinite(array)).count(False) - Sjotroll

3
如果你经常这样做,可以将其放入一个函数中,使其更易读和易于操作:
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

1

以下是一行lambda表达式:

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]

第一个非 NaN 值

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

第一个非 NaN 值的索引

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接