Skip to main content
 首页 » 编程设计

python之csr_matrix.sort_indices 有什么作用

2025年05月04日8qq号

我按以下方式制作 csr_matrix:

>>> A = sparse.csr_matrix([[0, 1, 0], 
                           [1, 0, 1], 
                           [0, 1, 0]]) 
>>> A[2,:] = np.array([-1, -2, -3]) 
 
>>> A.indptr 
Out[12]: array([0, 1, 3, 6], dtype=int32) 
>>> A.indices 
Out[13]: array([1, 0, 2, 0, 2, 1], dtype=int32) 
>>> A.data 
Out[14]: array([ 1,  1,  1, -1, -3, -2], dtype=int64) 

现在我想交换 indices 和 data 数组中的最后两个元素,所以我尝试:

>>> A.sort_indices() 

但这对我的矩阵没有任何作用。 manual因为此函数仅说明它对索引进行排序。

  1. 这个功能是做什么的?在哪种情况下您可以看出差异?
  2. 如何对 indices 和 data 数组进行排序,以便对每一行的索引进行排序?

请您参考如下方法:

如文档中所述,A.sort_indices() 对索引进行就地排序。但是有一个缓存:if A.has_sorted_indices is True, it won't do anything (缓存是 introduced at 0.7.0 )。

因此,为了看到差异,您需要手动将 A.has_sorted_indices 设置为 False。

>>> A.has_sorted_indices, A.indices 
(True, array([1, 0, 2, 0, 2, 1], dtype=int32)) 
>>> A.sort_indices() 
>>> A.has_sorted_indices, A.indices 
(True, array([1, 0, 2, 0, 2, 1], dtype=int32)) 
>>> A.has_sorted_indices = False 
>>> A.sort_indices() 
>>> A.has_sorted_indices, A.indices 
(True, array([1, 0, 2, 0, 1, 2], dtype=int32)) 

请注意,与 OP 指出的不同,从 SciPy 0.19.0 开始运行 A[2, :] = [-1, -2, -3] 不再产生错误-订单索引(this should have been fixed in 0.14.0)。另一方面,此操作会产生警告:

SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.

无论如何,我们可以通过其他方式轻松生成乱序索引,例如通过矩阵乘法:

>>> B = scipy.sparse.csr_matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) 
>>> C = B*B 
>>> C.has_sorted_indices, C.indices 
(0, array([2, 0, 1, 2, 0], dtype=int32)) 
>>> C.sort_indices() 
>>> C.has_sorted_indices, C.indices 
(True, array([0, 2, 1, 0, 2], dtype=int32))