float(nan')表示nan(不是数字)。但我该如何检查呢?
当前回答
似乎检查它是否等于自身(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(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,而无需对右侧求值。
对于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
这里有三种方法可以测试变量是否为“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
事实上我刚碰到这个,但对我来说,它是在检查nan、-inf或inf
if float('-inf') < float(num) < float('inf'):
这对于数字是正确的,对于nan和inf都是错误的,对于字符串或其他类型(这可能是一件好事)会引发异常。此外,这不需要导入任何库,如math或numpy(numpy非常大,它的大小是任何编译应用程序的两倍)。
下面是一个答案:
符合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