如何获取numpy数组中所有NaN值的索引列表?

xxx*_*222 51 python numpy scipy

说现在我有一个numpy数组,定义为,

[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
Run Code Online (Sandbox Code Playgroud)

现在我想要一个包含缺失值的所有索引的列表,[(1,2),(2,0)]在这种情况下.

有什么方法可以做到吗?

mic*_*ard 91

np.isnannp.argwhere相结合

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))
Run Code Online (Sandbox Code Playgroud)

输出:

array([[1, 2],
       [2, 0]])
Run Code Online (Sandbox Code Playgroud)


joh*_*d12 19

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

np.argwhere(x!=x)
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*eli 17

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

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
Run Code Online (Sandbox Code Playgroud)