How to Check If String is NaN in Python

NaN in Python is a numeric data type member representing an unpredictable value. NaN is a “Not a Number” representing an undefined value in the computing system.

To represent any missing value in Python, use the NaN.

Check If String is NaN in Python

To check if a string is NaN in Python, use the != operator. The != operator returns True if the given argument is a NaN and returns False otherwise.

import numpy as np

def checkNaN(str):
  return str != str




To create a NaN value in Python, use np.nan.

In this example, we defined the checkNaN() function that returns True if the string is NaN; otherwise, it returns False.

You can see that the np.nan value returns True, and the “AppDividend” string returns False.

Using math.isnan() function

The math.isnan() is a built-in Python function that checks if the value is NaN or not. The math.isnan() function returns the Boolean value, which returns True if the specified value is a NaN; otherwise, False.

import numpy as np
import math

def checkNaN(str):
    return math.isnan(float(str))
    return False


To handle a ValueError exception, use the try-except blockTo convert any value to a float value in Python, use the float() function.

In the above example, we defined a checkNaN() function that returns True if the string is NaN; otherwise False.

That’s it.

Related posts


Python check nan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.