Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sparse arrays from tuples

I searched the net to find a guide for Scipy sparse matrices and I failed. I would be happy if anybody would share any source for it but now going to question:

I have an array of tuples. I want to change the array of tuples to a sparse matrix where the tuples appear on the main diagonal and diagonal just beside to it as the following example shows it. What is the fancy(efficient) way of doing it?

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

Output being:

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]
like image 804
Cupitor Avatar asked Feb 15 '23 14:02

Cupitor


2 Answers

You can build those really fast as a CSR matrix:

>>> 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]])
like image 60
Jaime Avatar answered Feb 17 '23 04:02

Jaime


Try 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])

When I print B.todense(), it gives me

[[ 1.  2.  0.  0.  0.]
 [ 0.  3.  4.  0.  0.]
 [ 0.  0.  5.  6.  0.]
 [ 0.  0.  0.  7.  8.]]
like image 21
Prashant Kumar Avatar answered Feb 17 '23 04:02

Prashant Kumar