np.isnan for array in Python 中的数组



我有一个数组,我想将其更改为真值和假值的数组,以删除nan值。

当使用np.isnan尝试如下

时,可以:
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])

但是当我尝试在我的数组上做同样的事情时,它不起作用:

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

我怀疑,鉴于错误,这与对象类型有关,但我不确定具体如何。

请注意,当尝试math.isnan时,它似乎只接受单个值:

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

任何帮助将不胜感激!

将数组转换为 float 这将起作用:

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]

最新更新