float(nan')表示nan(不是数字)。但我该如何检查呢?
当前回答
另一种方法是,如果你坚持低于2.6,你没有numpy,也没有IEEE 754支持:
def isNaN(x):
return str(x) == str(1e400*0)
其他回答
这里有三种方法可以测试变量是否为“NaN”。
import pandas as pd
import numpy as np
import math
# For single variable all three libraries return single boolean
x1 = float("nan")
print(f"It's pd.isna: {pd.isna(x1)}")
print(f"It's np.isnan: {np.isnan(x1)}}")
print(f"It's math.isnan: {math.isnan(x1)}}")
输出
It's pd.isna: True
It's np.isnan: True
It's math.isnan: True
另一种方法是,如果你坚持低于2.6,你没有numpy,也没有IEEE 754支持:
def isNaN(x):
return str(x) == str(1e400*0)
我进入这篇文章,因为我在功能方面遇到了一些问题:
math.isnan()
运行此代码时出现问题:
a = "hello"
math.isnan(a)
它引发了异常。我的解决方案是再做一次检查:
def is_nan(x):
return isinstance(x, float) and math.isnan(x)
判断变量是NaN还是None的所有方法:
无类型
In [1]: from numpy import math
In [2]: a = None
In [3]: not a
Out[3]: True
In [4]: len(a or ()) == 0
Out[4]: True
In [5]: a == None
Out[5]: True
In [6]: a is None
Out[6]: True
In [7]: a != a
Out[7]: False
In [9]: math.isnan(a)
Traceback (most recent call last):
File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
math.isnan(a)
TypeError: a float is required
In [10]: len(a) == 0
Traceback (most recent call last):
File "<ipython-input-10-65b72372873e>", line 1, in <module>
len(a) == 0
TypeError: object of type 'NoneType' has no len()
NaN类型
In [11]: b = float('nan')
In [12]: b
Out[12]: nan
In [13]: not b
Out[13]: False
In [14]: b != b
Out[14]: True
In [15]: math.isnan(b)
Out[15]: True
如何从混合数据类型列表中删除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应用程序的最佳方法?