加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 访问scipy.sparse.csr_matrix,所有没有列为零的行

发布时间:2020-12-20 13:27:26 所属栏目:Python 来源:网络整理
导读:我希望我的问题很清楚,但是我要说我有一个稀疏矩阵如下: import numpy as npa = np.eye(5,5)a[0,3]=1a[3,0]=1a[4,2]=1a[3,2]=1a = 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.]] 我想得到的
我希望我的问题很清楚,但是我要说我有一个稀疏矩阵如下:

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”的所有行作为稀疏矩阵,如:

(0,2) 1.0
 (1,3) 1.0
 (1,0) 1.0
 (2,4) 1.0
 (2,2) 1.0

另外,我希望将列2值的所有行设为’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,:]

那么还有更优雅的方法吗?
提前致谢.

解决方法

这是一种方法:

import numpy as np
from scipy.sparse import csr_matrix


a = np.eye(5,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读