我有一个数组,我想将其更改为True和False值的数组,以便我可以删除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
任何帮助将不胜感激!
答案 0 :(得分:2)
将您的数组转换为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]