The Python Oracle

How can I check for NaN values?

--------------------------------------------------
Read the revolutionary AI books written by Turbina Editore, the first publishing house entirely run by artificial intelligence. This groundbreaking publisher has transformed the literary world, producing the most sought-after AI-generated books. Start reading today at:
https://turbinaeditore.com/en/
--------------------------------------------------

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 How Can I Check For Nan Values?
00:13 Accepted Answer Score 2215
00:23 Answer 2 Score 626
00:36 Answer 3 Score 305
00:45 Answer 4 Score 266
01:02 Thank you

--

Full question
https://stackoverflow.com/questions/9447...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #math

#avk47



ACCEPTED ANSWER

Score 2215


Use math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True



ANSWER 2

Score 626


The usual way to test for a NaN is to see if it's equal to itself:

def isNaN(num):
    return num != num



ANSWER 3

Score 305


numpy.isnan(number) tells you if it's NaN or not.




ANSWER 4

Score 266


Here are three ways where you can test a variable is "NaN" or not.

import pandas as pd
import numpy as np
import math

# For single variable all three libraries return single boolean
x1 = float("nan")

print(f"It's pd.isna: {pd.isna(x1)}")
print(f"It's np.isnan: {np.isnan(x1)}}")
print(f"It's math.isnan: {math.isnan(x1)}}")

Output:

It's pd.isna: True
It's np.isnan: True
It's math.isnan: True