Fad
Fad

Reputation: 29

different outputs for checking if a nan value is in the list or not

I have a list and I want to check if there is a missing value or not! I used two different ways to check it but didn't get the same outputs!

np.nan in lst1

output for this one is "False"

n = 0
for i in range(len(lst1)):
    if lst1[i] is np.nan :
        n+=1
print(n)

and for this one is 1!

the second answer is actually true but I don't know why in the first code I got "False"

Upvotes: 0

Views: 868

Answers (2)

Andy Pavlov
Andy Pavlov

Reputation: 316

To use math.isnan(x) is preferred way of NaN finding. As I understand np.nan and pure python NaN are not the same objects. And you get False at checking.

import math
import numpy as np

lst1 = [1,2,3, float('nan'), 2, np.nan, 4]
for ix, vl in enumerate(lst1):
    if math.isnan(vl):
        print(ix, vl)

for ix, vl in enumerate(lst1):
    if vl is np.nan:
        print(ix, vl)

Output for math.isnan()

3 nan
5 nan

Output for np.nan check

5 nan

Upvotes: 2

Rose Day
Rose Day

Reputation: 15

I am not sure what your lst1 looks like so I created my own and ran the examples above.

>>> import numpy as np
>>> lst1 = [1,2,3, np.nan, 2,3,4]
>>> np.nan in lst1
True

The function isin() can be looked at in the documentation here. This function looks to see if the element is contained in the list and will return True if it is. Without the original list you used, it is hard to determine how you got False.

I also ran the second portion of code you shared to make sure I was getting the same result, and I received 1 as the output there for the list I provided.

>>> for i in range(len(lst1)):
...     if lst1[i] is np.nan :
...         n+=1
... 
>>> print(n)
1

If you can provide your original list, that may be helpful to determine what the problem is.

Upvotes: 0

Related Questions