Difference between np.nan and np.NaN
Asked Answered
G

3

22

Is there any difference between np.Nan and np.nan? As per my understanding both are used for null values but if you look here

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame([[np.nan,2,np.nan,0],[3,4,np.nan,1],[np.nan,np.nan,np.nan,5]],columns=list('ABCD'))
print(df)
print(np.nan == np.NaN)

I get following output:

     A    B   C  D
0  NaN  2.0 NaN  0
1  3.0  4.0 NaN  1
2  NaN  NaN NaN  5
False

Process finished with exit code 0

Now if these are same print(np.nan == np.NaN) should return True and why are the values in dataframe populated as NaN?

I get NaN is not a number so it might be treating it that way and hence changing the entry in dataframe but I am still not sure.

Genital answered 22/11, 2018 at 18:14 Comment(5)
np.nan is np.NaN is True. They are alias.Zinn
In pycharm, I get false.Genital
@Genital You should not use equality to test nans, it will always return False. i.e. np.nan == np.nan is also False. But testing identity with is, np.nan is np.NaN is True. See IEEE 754 Floating Point Special Values in the NumPy docs.Dorris
both are used for null values - no. Not null. "Not a number".Milkwhite
Note that NaN ≠ NaN holds in any IEEE 754 compliant floating-point system. So you will find this behaviour almost anywhere you look, not just in Python. This goes all the way down to the CPU level. en.wikipedia.org/wiki/NaNUncovenanted
A
10

so basically NaN,NAN and nan are equivalent definitions of nan

or in other words

NaN and NAN are aliases of nan

np.nan
np.NaN
np.NAN

if you will check the equality of these it returns False

and if you check the types of all these 3 then you will find that all are of same type(float)

but let

a=np.NaN
b=np.NAN
c=np.nan

now if you will check the equality of a,b and c it returns True (it won't work now)

Even in the documentation(line 4) it is said that:-

cannot use equality to test NaNs

you can check the documentation from here:-

https://numpy.org/doc/stable/user/misc.html?highlight=numpy%20nan

Aeonian answered 13/2, 2021 at 16:42 Comment(1)
Actually, a == b returns False as well. Likewise for c.Lir
R
3
  • When you try: np.nan is np.NAN is np.NaN, you will get true
  • I have searched the offical doc of numpy , it says:
    • IEEE 754 floating point representation of Not a Number (NaN). NaN and NAN are equivalent definitions of nan. Please use nan instead of NaN.
    • IEEE 754 floating point representation of Not a Number (NaN). NaN and NAN are equivalent definitions of nan. Please use nan instead of NAN.
Rufford answered 12/12, 2022 at 8:9 Comment(0)
B
1

actually even if you test: np.nan == np.nan you would get false

Beach answered 19/6, 2021 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.