现在说我有一个numpy数组,定义为,
[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
现在我想要一个包含缺失值的所有索引的列表,在这种情况下为[(1,2),(2,0)]
。
我有什么方法可以做到吗?
答案 0 :(得分:78)
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]])
答案 1 :(得分:14)
您可以使用MDN来匹配与数组的Nan
值对应的布尔条件,并使用map
每个结果来生成tuples
的列表。
>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
答案 2 :(得分:3)
由于x!=x
返回与np.isnan(x)
相同的布尔数组(因为np.nan!=np.nan
将返回True
),因此您还可以编写:
np.argwhere(x!=x)
但是,我仍然建议编写np.argwhere(np.isnan(x))
,因为它更具可读性。我只是尝试提供在此答案中编写代码的另一种方法。