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
>>>
-
41
-
5this fails if the string that is being tested to be a number, isn't a number. Need to use isdigit in those cases. – Joel Jan 14 '13 at 18:57
-
3@charlie-parker : In Python3, math.isnan is still a part of the math module. docs.python.org/3/library/math.html#math.isnan . Use numpy.isnan if you wish, this answer is just a suggestion. – gimel Sep 8 '16 at 4:43
-
15
-
9@TMWP possibly...
import numpy
takes around 15 MB of RAM, whereasimport math
takes some 0,2 MB – petrpulc Sep 12 '17 at 12:09
The usual way to test for a NaN is to see if it's equal to itself:
def isNaN(num):
return num != num
-
8Word of warning: quoting Bear's comment below "For people stuck with python <= 2.5. Nan != Nan did not work reliably. Used numpy instead." Having said that, I've not actually ever seen it fail. – mavnn Jan 26 '10 at 13:18
-
14I'm sure that, given operator overloading, there are lots of ways I could confuse this function. go with math.isnan() – djsadinoff Aug 11 '11 at 22:38
-
4It says in the 754 spec mentioned above that NaN==NaN should always be false, although it is not always implemented as such. Isn't is possible this is how math and/or numpy check this under the hood anyway? – Hari Ganesan Apr 1 '14 at 16:16
numpy.isnan(number)
tells you if it's NaN
or not in Python 2.5.
-
3
-
6
numpy.all(numpy.isnan(data_list))
is also useful if you need to determine if all elements in the list are nan – Jay P. Feb 27 '14 at 22:18 -
2
-
5When this answer was written 6 years ago, Python 2.5 was still in common use - and math.isnan was not part of the standard library. Now days I'm really hoping that's not the case in many places! – mavnn Mar 30 '15 at 7:30
-
2note that np.isnan() doesn't handle decimal.Decimal type (as many numpy's function). math.isnan() does handle. – comte May 16 '18 at 15:53
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).
-
6
math.isfinite
was not introduced until Python 3.2, so given the answer from @DaveTheScientist was posted in 2012 it was not exactly "reinvent[ing] the wheel" - solution still stands for those working with Python 2. – sudo_coffee Nov 22 '16 at 17:09
or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.
-
5For people stuck with python <= 2.5. Nan != Nan did not work reliably. Used numpy instead. – Bear Jan 18 '10 at 7:06
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
-
The series I'm checking is strings with missing values are 'nans' (???) so this solution works where others failed. – keithpjolley Nov 3 '18 at 22:49
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)
-
1
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)
-
1It was probably downvoted because isnan() takes a float, not a string. There's nothing wrong with the function, and the problems are only in his attempted use of it. (For that particular use case his solution is valid, but it's not an answer to this question.) – Peter Hansen Jul 7 '13 at 14:12
-
6Be careful with checking for types in this way. This will not work e.g. for numpy.float32 NaN's. Better to use a try/except construction:
def is_nan(x): try: return math.isnan(x) except: return False
– Rob Mar 24 '14 at 10:25 -
2NaN does not mean that a value is not a valid number. It is part of IEEE floating point representation to specify that a particular result is undefined. e.g. 0 / 0. Therefore asking if "hello" is nan is meaningless. – Brice M. Dempsey Jul 17 '15 at 8:50
-
1this is better because NaN can land in any list of strings,ints or floats, so useful check – RAFIQ Mar 11 '16 at 8:41
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
-
4
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
-
-
-
Well, being "not a number", anything that can not be casted to an int I guess is in fact not a number, and the try statement will fail? Try, return true, except return false. – chwi Jul 7 '16 at 9:29
-
@chwi Well, taking "not a number" literally, you are right, but that's not the point here. In fact, I am looking exactly for what the semantics of
NaN
is (like in python what you could get fromfloat('inf') * 0
), and thus although the string 'Hello' is not a number, but it is also notNaN
becauseNaN
is still a numeric value! – Mahdi Jul 7 '16 at 11:19
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
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
How to remove NaN (float) item(s) from a list of mixed data types
If you have mixed types in an iterable, here is a solution that does not use numpy:
from math import isnan
Z = ['a','b', float('NaN'), 'd', float('1.1024')]
[x for x in Z if not (
type(x) == float # let's drop all float values…
and isnan(x) # … but only if they are nan
)]
['a', 'b', 'd', 1.1024]
Short-circuit evaluation means that isnan
will not be called on values that are not of type 'float' as (False and …
quickly evaluates to False
without having to evaluate the right-hand side.
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
protected by eyllanesc Jul 17 '18 at 5:44
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
numpy.isnan(numpy.nan)
will then returnTrue
. And obviously,import numpy
before doing that. :) – John Strood Feb 7 '18 at 10:09