如何检查NaN值?

时间:2021-07-05 12:17:54

float('nan') results in Nan (not a number). But how do I check for it? Should be very easy, but I cannot find it.

float('nan')导致Nan(不是数字)。但我该如何检查呢?应该很容易,但我找不到它。

13 个解决方案

#1


math.isnan()

Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.

检查浮点x是否为NaN(不是数字)。 NaN是IEEE 754标准的一部分。操作类似于但不限于inf * 0,inf / inf或涉及NaN的任何操作,例如, nan * 1,返回NaN。

New in version 2.6.

版本2.6中的新功能。

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

#2


The usual way to test for a NaN is to see if it's equal to itself:

测试NaN的常用方法是查看它是否与自身相同:

def isNaN(num):
    return num != num

#3


numpy.isnan(number) tells you if it's NaN or not in Python 2.5.

numpy.isnan(number)告诉你它是否在Python 2.5中是NaN。

#4


I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used

我实际上只是碰到了这个,但对我来说,它正在检查nan,-inf或inf。我刚刚用过

if float('-inf') < float(num) < float('inf'):

This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).

这对于数字来说是正确的,对于nan和inf都是假的,并且会为字符串或其他类型(这可能是一件好事)引发异常。此外,这不需要导入任何库,如数学或numpy(numpy太大了,它的任何编译应用程序的大小翻倍)。

#5


math.isnan()

or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.

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

#6


here is an answer working with:

这是一个答案:

  • python non-unique NaN: float('nan')
  • python非唯一NaN:float('nan')

  • numpy unique NaN (singleton) : np.nan
  • numpy unique NaN(singleton):np.nan

  • any other objects: string or whatever (does not raise exceptions if encountered)
  • 任何其他对象:字符串或其他任何东西(如遇到则不引发异常)

Here it is:

这里是:

import numpy as np

def is_nan(x):
    return (x is np.nan or x != x)

And some examples:

还有一些例子:

values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print "{:<8} : {}".format(repr(value), is_nan(value))

Output:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False

#7


Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support:

另一种方法,如果你坚持<2.6,你没有numpy,并且你没有IEEE 754支持:

def isNaN(x):
    return str(x) == str(1e400*0)

#8


With python < 2.6 I ended up with

随着python <2.6,我最终得到了

def isNaN(x):
    return str(float(x)).lower() == 'nan'

This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10

这适用于Solaris 5.9机器上的python 2.5.1和Ubuntu 10上的python 2.6.5

#9


Well I entered this post, because i've had some issues with the function:

好吧,我进入了这篇文章,因为我的功能存在一些问题:

math.isnan()

There are problem when you run this code:

运行此代码时出现问题:

a = "hello"
math.isnan(a)

It raises exception. My solution for that is to make another check:

它引发了例外。我的解决方案是再次检查:

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

#10


I am receiving the data from a web-service that sends NaN as a string 'Nan'. But there could be other sorts of string in my data as well, so a simple float(value) could throw an exception. I used the following variant of the accepted answer:

我从Web服务接收数据,该服务将NaN作为字符串'Nan'发送。但是我的数据中可能还有其他类型的字符串,因此简单的float(value)可能会抛出异常。我使用了以下接受的答案变体:

def isnan(value):
  try:
      import math
      return math.isnan(float(value))
  except:
      return False

Requirement:

isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True

#11


All the methods to tell if the variable is NaN or None:

判断变量是NaN还是None的所有方法:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

#12


For nan of type float

对于纳米型浮子

>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False

#13


for strings in panda take pd.isnull:

对于熊猫中的字符串,请参阅pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

该功能作为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

#1


math.isnan()

Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.

检查浮点x是否为NaN(不是数字)。 NaN是IEEE 754标准的一部分。操作类似于但不限于inf * 0,inf / inf或涉及NaN的任何操作,例如, nan * 1,返回NaN。

New in version 2.6.

版本2.6中的新功能。

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

#2


The usual way to test for a NaN is to see if it's equal to itself:

测试NaN的常用方法是查看它是否与自身相同:

def isNaN(num):
    return num != num

#3


numpy.isnan(number) tells you if it's NaN or not in Python 2.5.

numpy.isnan(number)告诉你它是否在Python 2.5中是NaN。

#4


I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used

我实际上只是碰到了这个,但对我来说,它正在检查nan,-inf或inf。我刚刚用过

if float('-inf') < float(num) < float('inf'):

This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).

这对于数字来说是正确的,对于nan和inf都是假的,并且会为字符串或其他类型(这可能是一件好事)引发异常。此外,这不需要导入任何库,如数学或numpy(numpy太大了,它的任何编译应用程序的大小翻倍)。

#5


math.isnan()

or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.

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

#6


here is an answer working with:

这是一个答案:

  • python non-unique NaN: float('nan')
  • python非唯一NaN:float('nan')

  • numpy unique NaN (singleton) : np.nan
  • numpy unique NaN(singleton):np.nan

  • any other objects: string or whatever (does not raise exceptions if encountered)
  • 任何其他对象:字符串或其他任何东西(如遇到则不引发异常)

Here it is:

这里是:

import numpy as np

def is_nan(x):
    return (x is np.nan or x != x)

And some examples:

还有一些例子:

values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print "{:<8} : {}".format(repr(value), is_nan(value))

Output:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False

#7


Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support:

另一种方法,如果你坚持<2.6,你没有numpy,并且你没有IEEE 754支持:

def isNaN(x):
    return str(x) == str(1e400*0)

#8


With python < 2.6 I ended up with

随着python <2.6,我最终得到了

def isNaN(x):
    return str(float(x)).lower() == 'nan'

This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10

这适用于Solaris 5.9机器上的python 2.5.1和Ubuntu 10上的python 2.6.5

#9


Well I entered this post, because i've had some issues with the function:

好吧,我进入了这篇文章,因为我的功能存在一些问题:

math.isnan()

There are problem when you run this code:

运行此代码时出现问题:

a = "hello"
math.isnan(a)

It raises exception. My solution for that is to make another check:

它引发了例外。我的解决方案是再次检查:

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

#10


I am receiving the data from a web-service that sends NaN as a string 'Nan'. But there could be other sorts of string in my data as well, so a simple float(value) could throw an exception. I used the following variant of the accepted answer:

我从Web服务接收数据,该服务将NaN作为字符串'Nan'发送。但是我的数据中可能还有其他类型的字符串,因此简单的float(value)可能会抛出异常。我使用了以下接受的答案变体:

def isnan(value):
  try:
      import math
      return math.isnan(float(value))
  except:
      return False

Requirement:

isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True

#11


All the methods to tell if the variable is NaN or None:

判断变量是NaN还是None的所有方法:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

#12


For nan of type float

对于纳米型浮子

>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False

#13


for strings in panda take pd.isnull:

对于熊猫中的字符串,请参阅pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

该功能作为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