Skip to main content
 首页 » 编程设计

python之从 Scipy 稀疏矩阵中获取唯一行

2025年02月15日8pander-it

我在 python 中使用稀疏矩阵,我想知道是否有一种有效的方法可以删除稀疏矩阵中的重复行,并且只保留唯一的行。

我没有找到与之关联的函数,并且不确定如何在不将稀疏矩阵转换为密集矩阵并使用 numpy.unique 的情况下执行此操作。

请您参考如下方法:

没有快速的方法,所以我不得不写一个函数。它返回一个稀疏矩阵,其中包含输入稀疏矩阵的唯一行(轴=0)或列(轴=1)。 请注意,返回矩阵的唯一行或列不是按字典顺序排序的(与 np.unique 的情况一样)。

import numpy as np 
import scipy.sparse as sp 
 
def sp_unique(sp_matrix, axis=0): 
    ''' Returns a sparse matrix with the unique rows (axis=0) 
    or columns (axis=1) of an input sparse matrix sp_matrix''' 
    if axis == 1: 
        sp_matrix = sp_matrix.T 
 
    old_format = sp_matrix.getformat() 
    dt = np.dtype(sp_matrix) 
    ncols = sp_matrix.shape[1] 
 
    if old_format != 'lil': 
        sp_matrix = sp_matrix.tolil() 
 
    _, ind = np.unique(sp_matrix.data + sp_matrix.rows, return_index=True) 
    rows = sp_matrix.rows[ind] 
    data = sp_matrix.data[ind] 
    nrows_uniq = data.shape[0] 
 
    sp_matrix = sp.lil_matrix((nrows_uniq, ncols), dtype=dt)  #  or sp_matrix.resize(nrows_uniq, ncols) 
    sp_matrix.data = data 
    sp_matrix.rows = rows 
 
    ret = sp_matrix.asformat(old_format) 
    if axis == 1: 
        ret = ret.T         
    return ret 
 
 
def lexsort_row(A): 
    ''' numpy lexsort of the rows, not used in sp_unique''' 
    return A[np.lexsort(A.T[::-1])] 
 
if __name__ == '__main__':     
    # Test 
    # Create a large sparse matrix with elements in [0, 10] 
    A = 10*sp.random(10000, 3, 0.5, format='csr') 
    A = np.ceil(A).astype(int) 
 
    # unique rows 
    A_uniq = sp_unique(A, axis=0).toarray() 
    A_uniq = lexsort_row(A_uniq) 
    A_uniq_numpy = np.unique(A.toarray(), axis=0) 
    assert (A_uniq == A_uniq_numpy).all() 
 
    # unique columns 
    A_uniq = sp_unique(A, axis=1).toarray() 
    A_uniq = lexsort_row(A_uniq.T).T 
    A_uniq_numpy = np.unique(A.toarray(), axis=1) 
    assert (A_uniq == A_uniq_numpy).all()