4

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.]]
2
  • Probably this is the silliest way I guess. Commented Nov 21, 2013 at 16:22
  • The primary source of information on the scipy sparse package is its reference page: docs.scipy.org/doc/scipy/reference/sparse.html. However this not a refined user or beginners guide. Keep in mind that this package is still under development. Matlab's sparse matricies might have better documentation. Commented Nov 21, 2013 at 18:19

2 Answers 2

4

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. Could you please give me also a source for this sparse matrices if you know any.
The wikipedia page on sparse matrices is a great starting point on what those three arrays (data, indices and indptr) are. Getting to know them often enables doing things that are (at least currently) beyond the sipy.sparse API in a very quick manner.
4

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.]]

1 Comment

More compactly: sparse.diags(A.T,[0,1],(4,5)).A

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.