Building and updating a sparse matrix in python using scipy

后端 未结 3 579
北海茫月
北海茫月 2020-12-24 14:39

I\'m trying to build and update a sparse matrix as I read data from file. The matrix is of size 100000X40000

What is the most efficient way of updating

3条回答
  •  庸人自扰
    2020-12-24 15:15

    Creating a second matrix with 1s in your new coordinates and adding it to the existing one is a possible way of doing this:

    >>> import scipy.sparse as sps
    >>> shape = (1000, 2000)
    >>> rows, cols = 1000, 2000
    >>> sps_acc = sps.coo_matrix((rows, cols)) # empty matrix
    >>> for j in xrange(100): # add 100 sets of 100 1's
    ...     r = np.random.randint(rows, size=100)
    ...     c = np.random.randint(cols, size=100)
    ...     d = np.ones((100,))
    ...     sps_acc = sps_acc + sps.coo_matrix((d, (r, c)), shape=(rows, cols))
    ... 
    >>> sps_acc
    <1000x2000 sparse matrix of type ''
        with 9985 stored elements in Compressed Sparse Row format>
    

提交回复
热议问题