Hello,
I am new to python. I have a naive question abount sparse matrix in python. How to save a scipy.sparse.csr.csr_matrix as csv or other format so that I can handle the matrix with R?
Hello,
I am new to python. I have a naive question abount sparse matrix in python. How to save a scipy.sparse.csr.csr_matrix as csv or other format so that I can handle the matrix with R?
I think you can use pandas
or numpy
to do this. I think if you;re using scipy
then you should have numpy
already installed (and you're probably using it now).
As an example:
# save numpy array as csv file
from numpy import asarray
from numpy import savetxt
# define data
data = asarray([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
# save to csv file
savetxt('data.csv', data, delimiter=',')
Reference documentation: https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html
There is a function in SciPy to convert sparse matrices and it is called todense:
import pandas as pd
from scipy.sparse.csr_matrix import todense
df = pd.DataFrame(data=todense(your_sparse_matrix_here))
df.to_csv('your_dense_matrix_name_here.csv', index=False)
Note that you may need large memory for this conversion depending on matrix dimensions.
Use of this site constitutes acceptance of our User Agreement and Privacy Policy.