努比。哪里对于该行不全为z的行索引

2024-04-26 21:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 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))

第一个数组是行索引吗?有没有更直接的方法只获取行索引?你知道吗


Tags: 方法np矩阵数组allwherearraydtype
2条回答

实际上,你自己已经接近解决方案了。你需要考虑一下你在np.where()里面做了什么。你知道吗

我以这个矩阵为例:

array([[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]),)

你做错的是用你得到的布尔矩阵来访问矩阵。你知道吗

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

array([[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()无法返回索引。它不知道你要什么。你知道吗

有一条直路:

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

相关问题 更多 >