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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:53:48  来源:igfitidea点击:

How to get the indices list of all NaN value in numpy array?

pythonnumpyscipy

提问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

np.isnan结合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

You can use np.whereto match the boolean conditions corresponding to Nanvalues of the array and mapeach outcome to generate a list of tuples.

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

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

回答by johnnyasd12

Since x!=xreturns the same boolean array with np.isnan(x)(because np.nan!=np.nanwould 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))因为它更具可读性。我只是尝试提供另一种方法来编写此答案中的代码。