Check if a given string is NaN in Python

Hi guys, today we will learn about NaN. In addition, we will learn about checking whether a given string is a NaN in Python. You will be wondering what’s this NaN. So let me tell you that Nan stands for Not a Number. It is a member of the numeric data type that represents an unpredictable value. For example, Square root of a negative number is a NaN, Subtraction of an infinite number from another infinite number is also a NaN. so basically, NaN represents an undefined value in a computing system.

How to Check if a string is NaN in Python

We can check if a string is NaN by using the property of NaN object that a NaN != NaN.

Let us define a boolean function isNaN() which returns true if the given argument is a NaN and returns false otherwise.

def isNaN(string):
    return string != string
print(isNaN("hello"))
print(isNaN(np.nan))

The output of the following code will be

False
True

We can also take a value and convert it to float to check whether it is NaN. For these, we import the math module and use the math.isnan() method. See the below code.

def isnan(value):
    try:
        import math
        return math.isnan(float(value))
    except:
        return False
print(isnan('hello'))
print(isnan('NaN'))
print(isnan(100)) 
print(isnan(str()))

Output:

False
True
False
False

A NaN can also be used to represent a missing value in computation. See the below code:

import numpy as np
l=['abc', 'xyz', 'pqr', np.nan]
print(l)
l_new=['missing' if x is np.nan else x for x in l]
print(l_new)

Output:

['abc', 'xyz', 'pqr', nan]
['abc', 'xyz', 'pqr', 'missing']

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *