Advertisement
Advertisement


How can I check for NaN values?


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.

2018/10/07
1
1056
10/7/2018 7:50:30 PM

Accepted Answer

math.isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
2019/07/22
1368
7/22/2019 11:42:49 AM

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

def isNaN(num):
    return num != num
2009/06/03

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

2019/07/22

Here are three ways where you can test a variable is "NaN" or not.

import pandas as pd
import numpy as np
import math

#For single variable all three libraries return single boolean
x1 = float("nan")

print(f"It's pd.isna  : {pd.isna(x1)}")
print(f"It's np.isnan  : {np.isnan(x1)}")
print(f"It's math.isnan : {math.isnan(x1)}")

Output

It's pd.isna  : True
It's np.isnan  : True
It's math.isnan  : True
2020/06/20

here is an answer working with:

  • NaN implementations respecting IEEE 754 standard
    • ie: python's NaN: float('nan'), numpy.nan...
  • any other objects: string or whatever (does not raise exceptions if encountered)

A NaN implemented following the standard, is the only value for which the inequality comparison with itself should return True:

def is_nan(x):
    return (x != x)

And some examples:

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

Output:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False
2020/04/22

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

2012/09/25

Source: https://stackoverflow.com/questions/944700
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]