Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump a sparse matrix into a file

I have a scipy.sparse.csr matrix and would like to dump it to a CSV file. Is there a way to preserve the sparsity of the matrix and write it to a CSV?

like image 838
Dexter Avatar asked May 22 '11 11:05

Dexter


People also ask

How do you write a sparse matrix to a file in python?

Another way store a sparse matrix in Python is to write it in npz format. The . npz file format is a “zipped archive of files named after the variables they contain”. We can use sparse module's save_npz() function to write a sparse matrix into a file in npz format.

How do I save a sparse matrix in R?

One of the ways to save the sparse matrix is to save them as Mtx file, that stores matrix in MatrixMarket format. We can use writeMM function to save the sparse matrix object into a file. In this example, we save our toy sparse matrix into file named “sparse_matrix. mtx”.

How do you store a sparse matrix in python?

The function csr_matrix() is used to create a sparse matrix of compressed sparse row format whereas csc_matrix() is used to create a sparse matrix of compressed sparse column format.


1 Answers

SciPy includes functions that read/write sparse matrices in the MatrixMarket format via the scipy.io module, including mmwrite: http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmwrite.html

MatrixMarket is not CSV, but close. It consists of a one-line header that has #rows, #cols, # of nonzeros, followed by one line per nonzero. Each of these lines is the row index, column index, value. You could write a simple script that turns whitespace into commas and you'd have a CSV.

like image 133
Adam Avatar answered Nov 08 '22 05:11

Adam