Search code examples
pythonnumpyscipysparse-matrixnetworkx

How do I transform a "SciPy sparse matrix" to a "NumPy matrix"?


I am using a python function called "incidence_matrix(G)", which returns the incident matrix of graph. It is from Networkx package. The problem that I am facing is the return type of this function is "Scipy Sparse Matrix". I need to have the Incident matrix in the format of numpy matrix or array. I was wondering if there is any easy way of doing that or not? Or is there any built-in function that can do this transformation for me or not?

Thanks


Solution

  • The scipy.sparse.*_matrix has several useful methods, for example, if a is e.g. scipy.sparse.csr_matrix:

    • a.toarray() - Return a dense ndarray representation of this matrix. (numpy.array, recommended)
    • a.todense() - Return a dense matrix representation of this matrix. (numpy.matrix)

    Previously, these methods had shorthands (.A for .toarray(), and .M for .todense()), but these have been or will be deprecated as of Scipy v1.14.0.