Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for NaN values?

Tags:

python

math

float('nan') represents NaN (not a number). But how do I check for it?

like image 237
Jack Ha Avatar asked Jun 03 '09 13:06

Jack Ha


4 Answers

Use math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
like image 196
gimel Avatar answered Oct 19 '22 19:10

gimel


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

def isNaN(num):
    return num != num
like image 40
Chris Jester-Young Avatar answered Oct 19 '22 19:10

Chris Jester-Young


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

like image 254
mavnn Avatar answered Oct 19 '22 21:10

mavnn


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
like image 202
M. Hamza Rajput Avatar answered Oct 19 '22 21:10

M. Hamza Rajput