# How can I check for NaN values?

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

### Accepted Answer

Return

`True`

if x is a NaN (not a number), and`False`

otherwise.

```
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
```

Read more... Read less...

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

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

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

here is an answer working with:

- NaN implementations respecting IEEE 754 standard
- ie: python's NaN:
`float('nan')`

,`numpy.nan`

...

- ie: python's 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
```

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