来自元组的稀疏数组

时间:2013-11-21 16:21:07

标签: python arrays numpy scipy sparse-matrix

我在网上搜索了Scipy稀疏矩阵的指南,但我失败了。如果有人愿意分享任何消息来源,我会很高兴但现在会质疑:

我有一系列元组。我想将元组数组更改为稀疏矩阵,其中元组出现在主对角线上,对角线紧挨着它,如下例所示。这种花哨的(有效的)方式是什么?

import numpy as np
A=np.asarray([[1,2],[3,4],[5,6],[7,8]])
B=np.zeros((A.shape[0],A.shape[0]+1))
for i in range(A.shape[0]):
    B[i,i]=A[i,0]
    B[i,i+1]=A[i,1]
print B

输出为:

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]

2 个答案:

答案 0 :(得分:4)

尝试diags from scipy

import numpy as np
import scipy.sparse

A = np.asarray([[1,2],[3,4],[5,6],[7,8]])
B = scipy.sparse.diags([A[:,0], A[:,1]], [0, 1], [4, 5])

当我print B.todense()时,它会给我

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]

答案 1 :(得分:4)

你可以像CSR矩阵一样快速构建它们:

>>> A = np.asarray([[1,2],[3,4],[5,6],[7,8]])
>>> rows = len(A)
>>> cols = rows + 1
>>> data = A.flatten() # we want a copy
>>> indptr = np.arange(0, len(data)+1, 2) # 2 non-zero entries per row
>>> indices = np.repeat(np.arange(cols), [1] + [2] * (cols-2) + [1])
>>> import scipy.sparse as sps
>>> a_sps = sps.csr_matrix((data, indices, indptr), shape=(rows, cols))
>>> a_sps.A
array([[1, 2, 0, 0, 0],
       [0, 3, 4, 0, 0],
       [0, 0, 5, 6, 0],
       [0, 0, 0, 7, 8]])