Convert a numpy float64 sparse matrix to a pandas data frame
This ipython session shows one way you could do it. The two steps are: convert the sparse matrix to COO format, and then create the Pandas DataFrame using the .row
, .col
and .data
attributes of the COO matrix.
In [50]: data Out[50]: <15x15 sparse matrix of type '<class 'numpy.float64'>' with 11 stored elements in Compressed Sparse Row format>In [51]: print(data) (1, 12) 0.8581958095588134 (6, 12) 0.03828052946099181 (6, 14) 0.7908634838351427 (7, 1) 0.7995008873930302 (7, 11) 0.48477191537121145 (7, 13) 0.6226526443518743 (9, 4) 0.37242576669669103 (11, 1) 0.9604278557580955 (11, 5) 0.13285436036287313 (12, 11) 0.5631419223609928 (13, 8) 0.16481624650723847In [52]: import pandas as pd In [53]: c = data.tocoo() In [54]: df = pd.DataFrame({node1: c.row, node2: c.col, edge_weight: c.data}) In [55]: df Out[55]: node1 node2 edge_weight0 1 12 0.8581961 6 12 0.0382812 6 14 0.7908633 7 1 0.7995014 7 11 0.4847725 7 13 0.6226536 9 4 0.3724267 11 1 0.9604288 11 5 0.1328549 12 11 0.56314210 13 8 0.164816