python

Python check NaN values with and without using packages

In python, NaN is considered as a float value and it does not mean anything. A NaN is not an integer, also it is not equal to NONE or 0 in python. Here, we are showing code examples that can be useful to check whether the given value is NaN or not.

# By comparing itself
def is_nan(val):
  return val != val

nan_value = float("nan")
print(is_nan(nan_value))
# -> True

#Using math.isnan(Import math before using math.isnan)
import math

nan_value = float("NaN")
check_nan = math.isnan(nan_value)
print(check_nan)
# -> True

In the above code examples, we are not using any python library and created a function is_nan() that will take the value as a parameter and will compare the value with itself. If the value is NaN then it will return true and if the value is not NaN it will return false.

In the Python programming language, NaN is considered as a float value so we converted NaN first to the float function of python then passed it to the function that will check if the value is NaN or not.

import math

my_value = float("NaN")
is_nan_val = math.isnan(my_value)
print(is_nan_val)
# -> True
You can also use math.isnan() method to check whether a value is NaN or not. You need to import math module of python to use math.isnan() method. You can pass the value to this method as a parameter and it will return True if the value is NaN and False if the value is not NaN.
import numpy as np

value = float("nan")
check_nan = np.isnan(value)
If you are using NumPy in your python project, you can use numpy.isnan() method to check whether a value is NaN or not. In the above code we have imported numpy and used its method isnan() to check for NaN value.
import pandas as pd

value = float("nan")
check_isnan = pd.isna(value)
print(check_isnan)
# -> True
Pandas method isna() can be used to check NaN values. In the above code, we have a variable named value that contains a NaN value. We are passing this to pandas pd.isna() method which will return true for NaN values.
def check_nan(x):
    return str(float(x)).lower() == 'nan'
    
print(check_nan('nan'))
# -> True
This method to check NaN values can be used in Python 2 also. We pass our value to float() method and then convert the result to lowercase and then check if it is equal to 'nan'. If it returns true then the value is NaN.
Was this helpful?