how to condition on if a value is np.nan in python

You can check if a value is np.nan using the numpy package's isnan() function. Here is an example code snippet:

main.py
import numpy as np

value = np.nan

if np.isnan(value):
    print("Value is NaN")
else:
    print("Value is not NaN")
118 chars
9 lines

Output:

main.py
Value is NaN
13 chars
2 lines

Alternatively, you can also use the math.isnan() function to check if a value is NaN. But in order to use this function, you need to convert the value to a float first (if it is not already a float). Here is an example:

main.py
import math

value = float('nan')

if math.isnan(value):
    print("Value is NaN")
else:
    print("Value is not NaN")
119 chars
9 lines

Output:

main.py
Value is NaN
13 chars
2 lines

related categories

gistlibby LogSnag