-1

通常我可以使用 numpy.isnan() 检查 NaN:

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

但是对于包含字符串的数组,我怎样才能达到同样的效果呢?

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

1 回答 1

0

正如评论者所建议的,在数组中包含字符串导致所有元素都被默默地强制转换为字符串,包括现在为“nan”的 np.nan 值,可以通过 arr2==nan 找到:

print(arr1=='nan')

[[False False]
 [False False]
 [ True False]
 [False False]]
于 2020-04-01T14:18:35.977 回答