-1

Normally I can check for NaNs with numpy.isnan() :

import numpy as np

arr1 = np.array([[1, 2], [3, 4], [np.nan, 5]])
print(type(arr1))
print(np.isnan(arr1))

<class 'numpy.ndarray'>
[[False False]
 [False False]
 [ True False]]

But how can I achieve the same for an array which contains strings?

arr2 = np.array([[1, 2], [3, 4], [np.nan, 5], ['high', 'low']])
print(type(arr2))
print(np.isnan(arr2))

<class 'numpy.ndarray'>

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-4a4a4bc72076> in <module>
      1 array = np.array([[1, 2], [3, 4], [np.nan, 5], ['high', 'low']])
      2 print(type(array))
----> 3 print(np.isnan(array))

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''

1 Answers1

0

As suggested by the commentors, the inclusion of strings in the array has led to all elements to be silently coerced to strings, including the np.nan values which are now 'nan', and can be found with arr2==nan:

print(arr1=='nan')

[[False False]
 [False False]
 [ True False]
 [False False]]