【问题标题】:using float('nan') to represent missing values - safe?使用 float('nan') 表示缺失值 - 安全吗?
【发布时间】:2011-05-02 12:37:13
【问题描述】:

Python 3.1

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

我正在考虑使用float('nan') 来表示缺失值。安全吗?最后我会检查一下

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

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

我当然可以使用 None,但它需要我使用 try / except TypeError 进行每一次计算才能检测到它。我也可以使用Inf,但我更不确定它是如何工作的。

编辑:

@MSN 我知道使用 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

我想 NaN 选项仍然更快,不是吗?

【问题讨论】:

  • math.isnan(x)x!=x 更具可读性。

标签: python floating-point python-3.x


【解决方案1】:

这是安全的,但如果 FPU 必须接触 x,它可能会非常慢(因为某些硬件将 NaN 视为特殊情况):Is it a good idea to use IEEE754 floating point NaN for values which are not set?

【讨论】:

  • 我想如果我改为使用if检查每个表达式的缺失值,它不会更快?
  • @max,你能给我一个代码示例来说明你的意思吗?我不太明白这个问题。
  • @max,当然更简洁。至于性能差异,这是非常特定于平台的。
猜你喜欢
  • 2014-06-09
  • 2014-06-09
  • 2011-04-07
  • 1970-01-01
  • 2021-08-06
  • 2021-12-22
  • 2019-08-12
  • 1970-01-01
  • 2021-05-10
相关资源
最近更新 更多