Np. Isnan for Array in Python

Np. Isnan for Array in Python

I have an array which I want to change into an array of True and False values to I can remove nan values.

When trying this using np.isnan as follows it's fine:

import numpy as np

a = np.array([1.,2.,np.nan])

a
Out[4]: array([ 1.,  2., nan])

np.isnan(a)
Out[5]: array([False, False,  True])

But when I try to do the same on my array, it doesn't work:

a
Out[9]: 
array([73788400000.0, 80017300000.0, 83680400000.0, 84939700000.0,
       83877800000.0, 83911700000.0, 85368100000.0, 83808200000.0,
       85936400000.0, 85177800000.0, 82705400000.0, 82119100000.0,
       73935400.0, 64018400.0, 42796500.0, 43130000.0, 42637600.0,
       167911000.0, nan], dtype=object)
np.isnan(a)

Traceback (most recent call last):

  File "<ipython-input-10-f4b5b5e7f347>", line 1, in <module>
    np.isnan(a)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I suspect, given the error, this has something to do with the object type but I'm not sure how exactly.

Please note, when trying math.isnan, it only appears to take single values:

math.isnan(a)

Traceback (most recent call last):

  File "<ipython-input-11-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)

TypeError: only size-1 arrays can be converted to Python scalars

Any help would be greatly appreciated!

2

1 Answer

Convert your array to float and this will work:

import numpy as np

a = np.array([73788400000.0, 80017300000.0, 83680400000.0, 84939700000.0,
              83877800000.0, 83911700000.0, 85368100000.0, 83808200000.0,
              85936400000.0, 85177800000.0, 82705400000.0, 82119100000.0,
              73935400.0, 64018400.0, 42796500.0, 43130000.0, 42637600.0,
              167911000.0, np.nan], dtype=object)

res = np.isnan(a.astype(float))

# [False False False False False False False False False False False False
#  False False False False False False  True]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.