Sparse arrays from tuples

arrays, numpy, python, scipy, sparse-matrix

Solution

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

Problem

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

Original source