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
print(checkNaN(np.nan))
print(checkNaN("AppDividend"))
Output
True
False
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):
try:
return math.isnan(float(str))
except:
return False
print(checkNaN(np.nan))
print(checkNaN("AppDividend"))
To handle a ValueError exception, use the try-except block. To 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.