numpy.where用于行索引,该行不是全部为零

时间:2017-05-30 08:11:35

标签: python numpy

我有一个大矩阵,有些行都是零。我想获得不是全零的行的索引。我试过了

 idx = np.where(mymatrix[~np.all(mymatrix != 0, axis=1)])

得到了

 (array([  21,   21,   21, ..., 1853, 3191, 3191], dtype=int64),
  array([3847, 3851, 3852, ..., 4148, 6920, 6921], dtype=int64))

第一个数组是行索引吗?是否有更简单的方法来获得行索引?

2 个答案:

答案 0 :(得分:1)

有一条直道:

np.where(np.any(arr != 0, axis=1))

答案 1 :(得分:1)

你自己就足够接近解决方案了。你需要在np.where()内思考一下你的工作。

我以此矩阵为例:

  

数组([[1,1,1,1],          [2,2,2,2],          [0,0,0,0],          [3,3,3,3]])

# This will give you back a boolean array of whether your
# statement is true or false per raw
np.all(mymatrix != 0, axis=1)
  

array([True,True,False,True],dtype = bool)

现在,如果您将其提交给np.where(),它将返回您想要的输出:

np.where(np.all(mymatrix != 0, axis=1))
  

(array([0,1,3]),)

你做错了是尝试使用你得到的bool矩阵访问矩阵。

# This will give you the raws without zeros.
mymatrix[np.all(mymatrix != 0, axis=1)]
  

数组([[1,1,1,1],          [2,2,2,2],          [3,3,3,3]])

# While this will give you the raws with only zeros
mymatrix[~np.all(mymatrix != 0, axis=1)]

给定这样的数组,np.where()无法返回索引。它不知道你要求什么。