访问scipy.sparse.csr_矩阵,所有没有零列j的行

2024-05-20 01:52:37 发布

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

我希望我的问题是清楚的,但是假设我有一个稀疏矩阵,如下所示:

import numpy as np
a = np.eye(5, 5)
a[0,3]=1
a[3,0]=1
a[4,2]=1
a[3,2]=1
a = csr_matrix(a)
[[ 1.  0.  0.  1.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 1.  0.  1.  1.  0.]
 [ 0.  0.  1.  0.  1.]]

例如,我要得到的是,列2的值为“1”的所有行作为稀疏矩阵,如:

^{pr2}$

另外,我希望将列2的值设为“0”的所有行作为另一个稀疏矩阵,例如:

(0, 3)  1.0
(0, 0)  1.0
(1, 1)  1.0

我不确定我的代码是否有效,但目前我所做的是:

b = np.asarray(a.getcol(2).todense()).reshape(-1)
iPos = np.nonzero(b)[0]
iZero = np.nonzero(np.logical_not(b))[0]
a1 = a[iPos, :]
a0 = a[iZero, :]

那么,有没有更优雅的方式来做到这一点呢? 提前谢谢。在


Tags: 代码importnumpyasnp矩阵matrixeye
1条回答
网友
1楼 · 发布于 2024-05-20 01:52:37

这是一种方法:

import numpy as np
from scipy.sparse import csr_matrix


a = np.eye(5, 5)
a[0,3]=1
a[3,0]=1
a[4,2]=1
a[3,2]=1


a = csr_matrix(a)
dense = np.asarray(a.todense())
column = np.asarray(a.getcol(2).todense()).reshape(-1)


print "dense"
# operations on full dense matrix
print "1"
print csr_matrix( np.vstack([ line for line in dense if line[2] == 1 ]) )
print "2"
print csr_matrix( np.vstack([ line for line in dense if line[2] == 0 ]) )

print "sparse"
# Operations on sparse matrix
result1 = []
result2 = []
for irow in range(a.shape[0]):
    if column[irow] == 1:
        [ result1.append( (irow,indice) ) for indice in a[irow].indices   ]
    else :
        [ result2.append( (irow,indice) ) for indice in a[irow].indices   ]

print result1,result2

第一种方法非常紧凑,但使用完全密集的输入矩阵(如果处理大矩阵,这可能会很麻烦),而第二种方法仅适用于稀疏矩阵,但结果对象是元组列表,而不是scipy.sparse.matrix. 在

相关问题 更多 >