使用numpy在矩阵中查找哪些行的所有元素都为零 [英] Finding which rows have all elements as zeros in a matrix with numpy
问题描述
我有一个大的numpy
矩阵M
.矩阵的某些行的所有元素均为零,我需要获取这些行的索引.我正在考虑的天真的方法是遍历矩阵中的每一行,然后检查每个元素.但是,我认为有一种更好,更快的方法可以使用numpy
来完成此任务.希望您能提供帮助!
I have a large numpy
matrix M
. Some of the rows of the matrix have all of their elements as zero and I need to get the indices of those rows. The naive approach I'm considering is to loop through each row in the matrix and then check each elements. However I think there's a better and a faster approach to accomplish this using numpy
. I hope you can help!
推荐答案
这是一种方法.我假设已经使用import numpy as np
导入了numpy.
Here's one way. I assume numpy has been imported using import numpy as np
.
In [20]: a
Out[20]:
array([[0, 1, 0],
[1, 0, 1],
[0, 0, 0],
[1, 1, 0],
[0, 0, 0]])
In [21]: np.where(~a.any(axis=1))[0]
Out[21]: array([2, 4])
此答案略有不同:这是怎么回事:
如果数组中的任何值为"truthy",则any
方法将返回True.非零数字被认为是True,而0被认为是False.通过使用参数axis=1
,该方法将应用于每一行.对于示例a
,我们有:
The any
method returns True if any value in the array is "truthy". Nonzero numbers are considered True, and 0 is considered False. By using the argument axis=1
, the method is applied to each row. For the example a
, we have:
In [32]: a.any(axis=1)
Out[32]: array([ True, True, False, True, False], dtype=bool)
因此,每个值指示相应的行是否包含非零值. ~
运算符是二进制"not"或补码:
So each value indicates whether the corresponding row contains a nonzero value. The ~
operator is the binary "not" or complement:
In [33]: ~a.any(axis=1)
Out[33]: array([False, False, True, False, True], dtype=bool)
(给出相同结果的替代表达式是(a == 0).all(axis=1)
.)
(An alternative expression that gives the same result is (a == 0).all(axis=1)
.)
要获取行索引,我们使用where
函数.它返回参数为True的索引:
To get the row indices, we use the where
function. It returns the indices where its argument is True:
In [34]: np.where(~a.any(axis=1))
Out[34]: (array([2, 4]),)
请注意,where
返回了一个包含单个数组的元组. where
适用于n维数组,因此它总是返回一个元组.我们想要该元组中的单个数组.
Note that where
returned a tuple containing a single array. where
works for n-dimensional arrays, so it always returns a tuple. We want the single array in that tuple.
In [35]: np.where(~a.any(axis=1))[0]
Out[35]: array([2, 4])
这篇关于使用numpy在矩阵中查找哪些行的所有元素都为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!