This post will discuss how to check for NaN (not a number) in Python.

NaN are special values in Python that represent an undefined or invalid numerical result. They are not equal to or comparable with any other values, including themselves. In other words, NaN values are neither equal nor unequal, neither greater nor less than any other value. However, there are several ways to check for NaN values in Python:

1. Using math.isnan() function

A simple solution to check for a NaN in Python is using the mathematical function math.isnan() from the math module. It takes a number as an argument and returns a boolean value True if the specified parameter is a NaN, and False otherwise. For example:

Download  Run Code

2. Using numpy.isnan() function

Alternatively, we can use the third-party numpy module to check for NaN values in arrays using the numpy.isnan() function. It takes an array or an element as an argument and returns a boolean value (True or False) or an array of boolean values indicating whether the array or element is a NaN or not. For example:

3. Using pandas.isna() function

We can also use the third-party pandas module to check for NaN values. The pandas module has a function pandas.isna(), which takes an element as an argument and returns a boolean indicating whether the element is a NaN value or not. For example, the following code uses the pandas.isna() function to detect NaN values.

4. Using != operator

Interestingly, because of IEEE specifications, we can take advantage of NaN’s being never equal to itself. For example:

Download  Run Code

That’s all about checking for NaN values in Python.