float(nan')表示nan(不是数字)。但我该如何检查呢?


当前回答

我进入这篇文章,因为我在功能方面遇到了一些问题:

math.isnan()

运行此代码时出现问题:

a = "hello"
math.isnan(a)

它引发了异常。我的解决方案是再做一次检查:

def is_nan(x):
    return isinstance(x, float) and math.isnan(x)

其他回答

当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

对于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

math.isnan()

或将数字与自身进行比较。NaN总是!=NaN,否则(例如,如果是数字),比较应成功。

下面是一个答案:

符合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