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
更易读。 - adw