float(nan')表示nan(不是数字)。但我该如何检查呢?
当前回答
我正在从一个web服务接收数据,该服务将NaN作为字符串“NaN”发送。但我的数据中也可能有其他类型的字符串,所以简单的float(value)可能会引发异常。我使用了接受答案的以下变体:
def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False
要求:
isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True
其他回答
似乎检查它是否等于自身(x!=x)是最快的。
import pandas as pd
import numpy as np
import math
x = float('nan')
%timeit x != x
44.8 ns ± 0.152 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit math.isnan(x)
94.2 ns ± 0.955 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit pd.isna(x)
281 ns ± 5.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit np.isnan(x)
1.38 µs ± 15.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
我进入这篇文章,因为我在功能方面遇到了一些问题:
math.isnan()
运行此代码时出现问题:
a = "hello"
math.isnan(a)
它引发了异常。我的解决方案是再做一次检查:
def is_nan(x):
return isinstance(x, float) and math.isnan(x)
测试NaN的通常方法是查看它是否等于自身:
def isNaN(num):
return num != num
下面是一个答案:
符合IEEE 754标准的NaN实现例如:python的NaN:float(NaN'),numpy.NaN。。。任何其他对象:string或其他任何对象(遇到异常时不会引发异常)
按照标准实现的NaN是唯一一个与自身的不平等比较应返回True的值:
def is_nan(x):
return (x != x)
还有一些例子:
import numpy as np
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
print(f"{repr(value):<8} : {is_nan(value)}")
输出:
nan : True
nan : True
55 : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False
如何从混合数据类型列表中删除NaN(float)项
如果在可迭代的中有混合类型,这里有一个不使用numpy的解决方案:
from math import isnan
Z = ['a','b', float('NaN'), 'd', float('1.1024')]
[x for x in Z if not (
type(x) == float # let's drop all float values…
and isnan(x) # … but only if they are nan
)]
['a', 'b', 'd', 1.1024]
短路求值意味着不会对非“float”类型的值调用isnan,因为False和(…)很快求值为False,而无需对右侧求值。
推荐文章
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录
- 我如何告诉matplotlib我已经完成了一个情节?
- 如何在Python中记录源文件名称和行号
- Python: List vs Dict用于查找表
- 试图在Windows 10上运行Python时出现“权限被拒绝”
- 如何在Django中设置时区
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?