Sparse arrays from tuples
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.Aarray([[1, 2, 0, 0, 0], [0, 3, 4, 0, 0], [0, 0, 5, 6, 0], [0, 0, 0, 7, 8]])
Try diags
from scipy
import numpy as npimport scipy.sparseA = 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.]]