float('nan')
结果为 Nan(不是数字)。但是我该如何检查呢?应该很容易,但我找不到。
18 回答
True
如果 x 是 NaN(不是数字)则返回,False
否则返回。
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
测试 NaN 的常用方法是查看它是否等于自身:
def isNaN(num):
return num != num
numpy.isnan(number)
告诉你是NaN
不是。
以下是您可以测试变量是否为“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
这是一个答案:
- 符合 IEEE 754 标准的 NaN 实现
- 即:python的NaN:
float('nan')
,numpy.nan
...
- 即:python的NaN:
- 任何其他对象:字符串或其他对象(如果遇到不会引发异常)
遵循标准实现的 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
似乎检查它是否等于自身
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)
实际上,我只是遇到了这个问题,但对我来说,它正在检查 nan、-inf 或 inf。我刚用
if float('-inf') < float(num) < float('inf'):
这对于数字是正确的,对于 nan 和 inf 都是错误的,并且会引发字符串或其他类型的异常(这可能是一件好事)。此外,这不需要导入任何库,如 math 或 numpy(numpy 太大了,它会使任何已编译应用程序的大小增加一倍)。
或将数字与自身进行比较。NaN 总是 != NaN,否则(例如,如果它是一个数字)比较应该成功。
好吧,我进入了这篇文章,因为我对这个功能有一些问题:
math.isnan()
运行此代码时出现问题:
a = "hello"
math.isnan(a)
它引发了异常。我的解决方案是再次检查:
def is_nan(x):
return isinstance(x, float) and math.isnan(x)
另一种方法,如果你卡在 <2.6,你没有 numpy,你没有 IEEE 754 支持:
def isNaN(x):
return str(x) == str(1e400*0)
随着 python < 2.6 我最终得到
def isNaN(x):
return str(float(x)).lower() == 'nan'
这适用于我在 Solaris 5.9 机器上使用 python 2.5.1 和在 Ubuntu 10 上使用 python 2.6.5
我从一个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
如何从混合数据类型列表中删除 NaN(浮点)项
如果您在可迭代中混合了类型,这里有一个不使用 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]
短路评估意味着isnan
不会调用非“浮点”类型的值,因为无需评估右侧即可False and (…)
快速评估。False
判断变量是 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
在 Python 3.6 中检查字符串值 x math.isnan(x) 和 np.isnan(x) 会引发错误。因此,如果我事先不知道它是一个数字,我无法检查给定的值是否为 NaN。以下似乎解决了这个问题
if str(x)=='nan' and type(x)!='str':
print ('NaN')
else:
print ('non NaN')
比较pd.isna
,math.isnan
以及np.isnan
它们处理不同类型对象的灵活性。
下表显示是否可以使用给定方法检查对象类型:
+------------+-----+---------+------+--------+------+
| Method | NaN | numeric | None | string | list |
+------------+-----+---------+------+--------+------+
| pd.isna | yes | yes | yes | yes | yes |
| math.isnan | yes | yes | no | no | no |
| np.isnan | yes | yes | no | no | yes | <-- # will error on mixed type list
+------------+-----+---------+------+--------+------+
pd.isna
检查不同类型缺失值的最灵活方法。
没有一个答案涵盖pd.isna
. 虽然math.isnan
并且np.isnan
将返回True
值NaN
,但您无法检查不同类型的对象,如None
字符串或字符串。这两种方法都会返回错误,因此检查具有混合类型的列表会很麻烦。这pd.isna
很灵活,将为不同类型的类型返回正确的布尔值:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: missing_values = [3, None, np.NaN, pd.NA, pd.NaT, '10']
In [4]: pd.isna(missing_values)
Out[4]: array([False, True, True, True, True, False])
对于浮点类型的nan
>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False
对于 panda 中的字符串,取 pd.isnull:
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
NLTK 的特征提取功能
def act_features(atext):
features = {}
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
if word not in default_stopwords:
features['cont({})'.format(word.lower())]=True
return features