Tutorial :How can I check for NaN in Python?


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



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


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

def isNaN(num):      return num != num  


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


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



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


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)  


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


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


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


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


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)  


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  


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


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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »