# Tutorial :How can I check for NaN in Python? ### Question:

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

### Solution: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  >>>   ``

### Solution:2

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

``def isNaN(num):      return num != num  ``

### Solution:3

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

### Solution: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).

### Solution: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.

### Solution:6

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

### Solution:7

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

### Solution:8

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

### Solution: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)  ``

### Solution: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:

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

### Solution:11

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

None type

``In : from numpy import math    In : a = None  In : not a  Out: True    In : len(a or ()) == 0  Out: True    In : a == None  Out: True    In : a is None  Out: True    In : a != a  Out: False    In : 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 : 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 : b = float('nan')  In : b  Out: nan    In : not b  Out: False    In : b != b  Out: True    In : math.isnan(b)  Out: True  ``

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