Check for NaN values in Python
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:
|
1 2 3 4 5 6 7 |
import math x = float('nan') isNaN = math.isnan(x) print(isNaN) # True |
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:
|
1 2 3 4 5 6 7 |
import numpy as np x = float('nan') isNaN = np.isnan(x) print(isNaN) # True |
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.
|
1 2 3 4 5 6 7 |
import pandas as pd x = float('nan') isNaN = pd.isna(x) print(isNaN) # True |
4. Using != operator
Interestingly, because of IEEE specifications, we can take advantage of NaN’s being never equal to itself. For example:
|
1 2 3 4 5 6 7 8 |
def isNaN(num): return num != num x = float('nan') isnan = isNaN(x) print(isnan) # True |
That’s all about checking for NaN values in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)