Python 如何获取numpy数组中所有NaN值的索引列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37754948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the indices list of all NaN value in numpy array?
提问by xxx222
Say now I have a numpy array which is defined as,
现在说我有一个 numpy 数组,它被定义为,
[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
Now I want to have a list that contains all the indices of the missing values, which is [(1,2),(2,0)]
at this case.
现在我想要一个包含缺失值的所有索引的列表,[(1,2),(2,0)]
在这种情况下。
Is there any way I can do that?
有什么办法可以做到吗?
回答by michael_j_ward
np.isnancombined with np.argwhere
x = np.array([[1,2,3,4],
[2,3,np.nan,5],
[np.nan,5,2,3]])
np.argwhere(np.isnan(x))
output:
输出:
array([[1, 2],
[2, 0]])
回答by Nickil Maveli
回答by johnnyasd12
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
由于x!=x
返回与np.isnan(x)
(因为np.nan!=np.nan
会返回True
)相同的布尔数组,您还可以编写:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
但是,我仍然建议写作,np.argwhere(np.isnan(x))
因为它更具可读性。我只是尝试提供另一种方法来编写此答案中的代码。