float('nan')
的结果是Nan(不是一个数字)。但我如何检查呢?应该非常容易,但我找不到。
如果x是NaN(不是一个数字),返回
True
,否则返回False
。
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
这里是一个答案工作。
float('nan')
。np.nan
在这里,它是。
import numpy as np
def is_nan(x):
return (x is np.nan or x != x)
还有一些例子。
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
print "{:<8} : {}".format(repr(value), is_nan(value))
产出:
nan : True
nan : True
55 : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False
或不是。
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 。
真
是np.isan 。
是
这是数学.isan 。
真
或将数字与自身进行比较。NaN总是!=NaN,否则(例如,如果它*是一个数字)比较应该成功。
判断变量是NaN还是None的所有方法。
None type
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
我从一个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
如果在一个可迭代的对象中存在混合类型,这里有一个不使用 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
将不会被调用在不是类型为'float'的值上,因为False和(...)
很快就会评估为`False',而不必评估右侧。对于熊猫中的字符串,取 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