how to create a sparse matrix from lists of numbers
I have three lists namely A , B , C All these lists contain 97510 items . I need to create a sparse matrix like this
matrix[A[0]][B[0]] = C[0]
For example ,
A=[1,2,3,4,5]
B=[7,8,9,10,11]
C=[14,15,16,17,18]
I need to create a sparse matrix with
matrix[1][7] = 14 # (which is C[0]开发者_StackOverflow社区)
matrix[2][8] = 15 # and so on .....
I tried and python gives me an error saying that "Index values must be continuous"
How do I do it?
I suggest you have a look at the SciPy sparse matrices. E.g. a COO sparse matrix:
matrix = sparse.coo_matrix((C,(A,B)),shape=(5,5))
Note: I just took the COO matrix because it was in the example, you can take any other. You probably have to try which one is most suitable for your situation. They all differ in the way how the data is compressed and this has an influence on the performance of certain operations.
If you simply need a way how to get matrix[A[0]][B[0]] = C[0] you can use the following:
A=[1,2,3,4,5]
B=[7,8,9,10,11]
C=[14,15,16,17,18]
matrix = dict((v,{B[i]:C[i]}) for i, v in enumerate(A))
EDITED(thanx for gnibbler):
A = [1,2,3,4,5]
B = [7,8,9,10,11]
C = [14,15,16,17,18]
matrix = dict(((v, B[i]), C[i]) for i, v in enumerate(A))
It is very simple to use a dict, especially if you are willing to change the way you write the indices slightly
>>> A=[1,2,3,4,5]
>>> B=[7,8,9,10,11]
>>> C=[14,15,16,17,18]
>>> matrix=dict(((a,b),c) for a,b,c in zip(A,B,C))
>>> matrix[1,7]
14
>>> matrix[2,8]
15
>>>
Have a look at numpy/scipy which has support for sparse matrixes. See e.g. here
精彩评论