How to Compare NaN Values in Python?

Estimated read time 2 min read

To compare NaN (Not a Number) values in Python, you can use the math.isnan() function or the numpy.isnan() function, depending on your requirements. Here’s an example:

Using math.isnan():

import math

# Define NaN values
nan_value_1 = float('nan')
nan_value_2 = float('nan')

# Compare NaN values
is_equal = math.isnan(nan_value_1) and math.isnan(nan_value_2)

# Print the result
print(f"Are NaN values equal? {is_equal}")

Using numpy.isnan():

import numpy as np

# Define NaN values
nan_value_1 = np.nan
nan_value_2 = np.nan

# Compare NaN values
is_equal = np.isnan(nan_value_1) and np.isnan(nan_value_2)

# Print the result
print(f"Are NaN values equal? {is_equal}")

In both examples:

  1. Two NaN values are defined, nan_value_1 and nan_value_2.
  2. The math.isnan() function or numpy.isnan() function is used to check if each value is NaN.
  3. The result of the comparison is stored in the is_equal variable.
  4. Finally, the result is printed to the console.

Both math.isnan() and numpy.isnan() functions return True if the value passed to them is NaN and False otherwise. If you have only one NaN value to compare, you can use the respective function directly without the need for the and operator.

It’s important to note that NaN values are considered unequal to any other value, including other NaN values. So, when comparing NaN values, you should use the math.isnan() or numpy.isnan() function specifically designed for handling NaN values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply