+3 votes
in Programming Languages by (74.2k points)
I want to convert a CSR matrix to a dense matrix. What function should I use for this?

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.

Here is an example:

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> import pandas as pd
>>> r = np.array([0, 0, 1, 1, 2, 2, 2, 3, 4, 4, 5, 6, 6])
>>> c = np.array([0, 3, 4, 1, 3, 5, 6, 3, 1, 6, 0, 1, 3])
>>> data = np.array([1]*len(r))
>>> X = csr_matrix((data, (r, c)), shape=(7, 7))
>>> X
<7x7 sparse matrix of type '<class 'numpy.int64'>'
    with 13 stored elements in Compressed Sparse Row format>
>>> Y=X.todense()
>>> Y
matrix([[1, 0, 0, 1, 0, 0, 0],
        [0, 1, 0, 0, 1, 0, 0],
        [0, 0, 0, 1, 0, 1, 1],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 1, 0, 0, 0]])
>>> Z=X.toarray()
>>> Z
array([[1, 0, 0, 1, 0, 0, 0],
       [0, 1, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 1, 1],
       [0, 0, 0, 1, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 1, 0, 0, 0]])


...