如何得到所有 NaN 值的索引列表在数字数组?

现在我有一个数字数组,它的定义是,

[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]

现在我想要一个包含缺失值的所有索引的列表,在本例中是 [(1,2),(2,0)]

我能做到吗?

199307 次浏览

Isnan 与 < a href = “ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argwhere.html”> np.argwhere 结合

x = np.array([[1,2,3,4],
[2,3,np.nan,5],
[np.nan,5,2,3]])
np.argwhere(np.isnan(x))

产出:

array([[1, 2],
[2, 0]])

可以使用 np.where匹配与数组的 Nan值对应的布尔条件,使用 map匹配每个结果以生成 tuples列表。

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

由于 x!=x返回与 np.isnan(x)相同的布尔数组(因为 np.nan!=np.nan将返回 True) ,您还可以写:

np.argwhere(x!=x)

但是,我仍然建议编写 np.argwhere(np.isnan(x)),因为它更具可读性。我只是尝试提供另一种方法来编写这个答案中的代码。