How can I check for NaN values?

2018-12-31 21:47发布

问题:

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

回答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.

New in version 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:

def isNaN(num):
    return num != num


回答3:

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



回答4:

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

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).



回答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.



回答6:

here is an answer working with:

  • python non-unique NaN: float(\'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:

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


回答8:

With python < 2.6 I ended up with

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



回答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:

All the methods to tell if the variable is NaN or 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


回答11:

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:

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


回答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:

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

the function as feature extraction for 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 math