问题描述
我有一个非常大的稀疏矩阵,我想检索前10个值的行和列值。我在下面创建了一个小的样本矩阵来模拟这种情况。知道如何在以下示例中获得前3名吗?
import numpy as np
from scipy.sparse import csc_matrix
a = np.matrix([[7,2,0],[0,6],[1,4]])
m = csc_matrix(a)
(0,0) 7
(2,0) 1
(0,1) 2
(1,2) 6
(2,2) 4
预期
(0,0) 7
(1,2) 4
解决方法
有帮助吗?
如果只需要这些值:
n = 3
np.partition(np.asarray(a),a.size - n,axis=None)[-n:]
输出
array([4,6,7])
如果您需要职位
n = 3
[np.where(a == x) for x in np.partition(np.asarray(a),axis=None)[-n:]]
输出
[(array([2],dtype=int64),array([2],dtype=int64)),(array([1],(array([0],array([0],dtype=int64))]
,
In [32]: a = np.array([[7,2,0],[0,6],[1,4]])
In [33]: M = sparse.coo_matrix(a)
In [34]: M
Out[34]:
<3x3 sparse matrix of type '<class 'numpy.int64'>'
with 5 stored elements in COOrdinate format>
In [35]: print(M)
(0,0) 7
(0,1) 2
(1,2) 6
(2,0) 1
(2,2) 4
In [36]: M.data
Out[36]: array([7,1,4])
In [37]: idx = np.argsort(M.data)
In [38]: idx
Out[38]: array([3,4,0])
In [39]: idx = idx[-3:]
In [40]: M.data[idx]
Out[40]: array([4,7])
In [41]: M1 = sparse.coo_matrix((M.data[idx],(M.row[idx],M.col[idx])),M.shape
...: )
In [42]: M1
Out[42]:
<3x3 sparse matrix of type '<class 'numpy.int64'>'
with 3 stored elements in COOrdinate format>
In [43]: M1.A
Out[43]:
array([[7,4]])
In [44]: print(M1)
(2,2) 4
(1,2) 6
(0,0) 7
我使用的是coo
格式,因为在给定数据idx
的情况下更容易获得行/列值。对于csr/csc
indices
与data
匹配,但是indptr
的值将很难重新创建。