Skip to main content
How To Check NaN Value In Python

How To Check NaN Value In Python

in this post, We’ll learn how to check NAN value in python. The NaN stands for ‘Not A Number’ which is a floating-point value that represents missing data.

You can determine in Python whether a single value is NaN or NOT. There are methods that use libraries (such as pandas, math, and numpy) and custom methods that do not use libraries.

NaN stands for Not A Number, is one of the usual ways to show a value that is missing from a set of data. It is a unique floating-point value and can only be converted to the float type.

In this article, I will explain four methods to deal with NaN in python. 

In Python, we’ll look at the following methods for checking a NAN value.

  • Check Variable Using Custom method
  • Using math.isnan() Method
  • Using numpy.nan() Method
  • Using pd.isna() Method

What is NAN in Python

None is a data type that can be used to represent a null value or no value at all. None isn’t the same as 0 or False, nor is it the same as an empty string. In numerical arrays, missing values are NaN; in object arrays, they are None.

Using Custom Method

We can check the value is NaN or not in python using our own method. We’ll create a method and compare the variable to itself.

def isNaN(num):
    return num!= num

data = float("nan")
print(isNaN(data))

Output:

True

Using math.isnan()

The math.isnan() is a Python function that determines whether a value is NaN (Not a Number). If the provided value is a NaN, the isnan() function returns True. Otherwise, False is returned.

The Syntax:

math.isnan(num)

Let’s check a variable is NaN using python script.

import math
a = 2
b = -8
c = float("nan")

print(math.isnan(a))
print(math.isnan(b))
print(math.isnan(c))

Output:

False
False
True

Using Numpy nan()

The numpy.nan() method checks each element for NaN and returns a boolean array as a result.

Let’s check a NaN variable using NumPy method:

import numpy as np
a = 2
b = -8
c = float("nan")

print(np.nan(a))
print(np.nan(b))
print(np.nan(c))

Output:

False
False
True

Using Pandas nan()

The pd.isna() method checks each element for NaN and returns a boolean array as a result.

The below code is used to check a variable NAN using the pandas method:

import pandas as pd
a = 2
b = -8
c = float("nan")

print(pd.isna(a))
print(pd.isna(b))
print(pd.isna(c))

Output:

False
False
True

Leave a Reply

Your email address will not be published. Required fields are marked *