I have a Python list of row information for a sparse matrix. Each row is represented as a list of (column, value) tuples. Call it alist:
alist = [[(1,10), (3,-3)],
[(2,12)]]
How can I efficiently construct a scipy sparse matrix from this list of lists, resulting in a matrix like this:
0 10 0 -3
0 0 12 0
The obvious approach is to make a scipy.sparse.lil_matrix, which internally has this "list of lists" structure. But from the scipy.sparse.lil_matrix — SciPy v0.19.0 Reference Guide I see just three ways of constructing them:
- starting from a dense array
- starting from another sparse array
- just constructing an empty array
So the only way to get fresh data in is either to solve this problem with some other sparse matrix representation, or to start with a dense array, neither of which address the initial problem, and both of which seem likely to be less efficient representations than lil_matrix itself for this data.
I guess I can make an empty one, and use a loop to add values, but surely I'm missing something.
The scipy documentation is really frustrating when it comes to sparse matrices.
from Constructing sparse from list of lists of tuples
No comments:
Post a Comment