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


当前回答

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

其他回答

在Python 3.6中,检查字符串值x math.isnan(x)和np.issan(x)会引发错误。所以我无法检查给定值是否为NaN,如果我事先不知道它是一个数字。以下内容似乎解决了这个问题

if str(x)=='nan' and type(x)!='str':
    print ('NaN')
else:
    print ('non NaN')

当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

我正在从一个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

使用math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True