在NumPy数组中查找None和NaN的索引

6

我有一个数组,长这样:

array([[  1.,   2.,   None],
       [ nan,   4.,   5.]])

我正在尝试以下操作:

np.equal(A, None) #works and finds index of None correctly
np.equal(A, np.nan) #doesn't work
np.isnan(A) #errors out

错误信息为:
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''

我该如何处理这个问题,我正在尝试在给定的数组中找到None和nan的索引。

我的最终输出应该如下:

array([[False, False,  True],
       [True, False, False]], dtype=bool)

1
np.nan 是一个合适的浮点数,但 None 是一个对象。因此你的数组具有对象类型。 - hpaulj
1个回答

5
我们可以先将数组转换为浮点数类型,这将把None转换为NaN。然后可以在这个浮点数数组上使用numpy.isnan。
numpy.isnan(A.astype(float))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接