索引一个带有布尔值阵列的SciPy稀疏矩阵。

时间:2021-03-03 21:24:52

NumPy arrays can be indexed with an array of booleans to select the rows corresponding to True entries:

NumPy数组可以使用布尔值数组进行索引,以选择与真实条目对应的行:

>>> X = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> rows = np.array([True,False,True])
>>> X[rows]
array([[1, 2, 3],
       [7, 8, 9]])
>>> X[np.logical_not(rows)]
array([[4, 5, 6]])

But this seems not possible with SciPy sparse matrices; the indices are taken as numeric ones, so False select row 0 and True selects row 1. How can I get the NumPy-like behavior?

但这似乎不可能用SciPy稀疏矩阵;索引作为数字索引,因此False选择第0行,True选择第1行。我怎样才能得到这种麻木的行为呢?

1 个解决方案

#1


9  

You can use np.nonzero (or ndarray.nonzero) on your boolean array to get corresponding numerical indices, then use these to access the sparse matrix. Since "fancy indexing" on sparse matrices is quite limited compared to dense ndarrays, you need to unpack the rows tuple returned by nonzero and specify that you want to retrieve all columns using the : slice:

你可以用np。布尔数组上的nonzero(或ndarray.nonzero)获取相应的数值索引,然后使用它们访问稀疏矩阵。由于与密集的ndarray相比,稀疏矩阵上的“花哨索引”相当有限,所以需要解压缩非零返回的行元组,并指定要使用:slice来检索所有列:

>>> rows.nonzero()
(array([0, 2]),)
>>> indices = rows.nonzero()[0]
>>> indices
array([0, 2])
>>> sparse[indices, :]
<2x100 sparse matrix of type '<type 'numpy.float64'>'
        with 6 stored elements in LInked List format>

#1


9  

You can use np.nonzero (or ndarray.nonzero) on your boolean array to get corresponding numerical indices, then use these to access the sparse matrix. Since "fancy indexing" on sparse matrices is quite limited compared to dense ndarrays, you need to unpack the rows tuple returned by nonzero and specify that you want to retrieve all columns using the : slice:

你可以用np。布尔数组上的nonzero(或ndarray.nonzero)获取相应的数值索引,然后使用它们访问稀疏矩阵。由于与密集的ndarray相比,稀疏矩阵上的“花哨索引”相当有限,所以需要解压缩非零返回的行元组,并指定要使用:slice来检索所有列:

>>> rows.nonzero()
(array([0, 2]),)
>>> indices = rows.nonzero()[0]
>>> indices
array([0, 2])
>>> sparse[indices, :]
<2x100 sparse matrix of type '<type 'numpy.float64'>'
        with 6 stored elements in LInked List format>