现在说我有一个numpy数组,定义为
[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
现在,我想要一个包含缺失值的所有索引的列表,[(1,2),(2,0)]在这种情况下。
有什么办法可以做到吗?
Answers:
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))因为它更具可读性。我只是尝试提供在此答案中编写代码的另一种方法。