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


当前回答

测试NaN的通常方法是查看它是否等于自身:

def isNaN(num):
    return num != num

其他回答

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

numpy.isnan(数字)告诉你它是不是NaN。

测试NaN的通常方法是查看它是否等于自身:

def isNaN(num):
    return num != num

使用math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
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