FakeBrain FakeBrain - 3 months ago 9
Python Question

why don't I get index returns from list comprehension checking truth values?

So I have a numpy array with numeric values, floats to be exact and NaNs:

In [1]: type(myarray)
Out[1]: numpy.ndarray


now I want to check where there are NaNs in this array so I try:

nan_idx = [idx for idx, tf in enumerate(myarray) if not bool(tf)]


However this returns an empty list, but when I try:

np.where(pd.isnull(mayarray))[0]


I do get as output the index of each NaN

Why doesn't the first attempt produce any results?

NPE NPE
Answer

The reason your first snippet doesn't work is that bool(float) does not check for NaNs:

>>> float('NaN')
nan
>>> bool(float('NaN'))
True
>>> not bool(float('NaN'))
False

To check for NaNs, you could use `numpy.isnan' or the fact that a NaN doesn't compare equal to itself:

>>> numpy.isnan(float('NaN'))
True
>>> float('NaN') != float('NaN')
True
Comments