Search code examples
pythonlistsparse-matrix

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


Solution

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