代码之家  ›  专栏  ›  技术社区  ›  max

使用float(“nan”)表示缺少的值-安全吗?

  •  3
  • max  · 技术社区  · 14 年前

    Python 3.1

    我正在对一个缺少值的数据进行一些计算。任何涉及缺少值的计算都应导致缺少值。

    我想用 float('nan') 表示缺少的值。安全吗?最后我查一下

    def is_missing(x):
      return x!=x # I hope it's safe to use to check for NaN
    

    看起来很完美,但我在文档中找不到明确的确认。

    当然,我可以不使用任何一个,但是它需要我用 try / except TypeError 来检测它。我也可以用 Inf 但是我更不确定它是如何工作的。

    编辑:

    @我知道使用Nan很慢。但如果我的选择是:

    # missing value represented by NaN
    def f(a, b, c):
      return a + b * c
    

    # missing value represented by None
    def f(a, b, c):
      if a is None or b is None or c is None:
        return None
      else:
        return a + b * c
    

    我可以想象南部的选择仍然更快,不是吗?