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


当前回答

使用math.isnan:

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

其他回答

这里有三种方法可以测试变量是否为“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:

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

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

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