Question: How to save scipy.sparse.csr.csr_matrix as csv or other format to handle it with R?
0
gravatar for hq.huang11.6
16 days ago by
China/Xiamen/Xiamen university
hq.huang11.60 wrote:

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?

R python • 106 views
ADD COMMENTlink modified 16 days ago by Mensur Dlakic6.0k • written 16 days ago by hq.huang11.60
1
gravatar for Mark
16 days ago by
Mark800
Mark800 wrote:

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

ADD COMMENTlink written 16 days ago by Mark800
1
gravatar for Mensur Dlakic
16 days ago by
Mensur Dlakic6.0k
USA
Mensur Dlakic6.0k wrote:

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.

ADD COMMENTlink written 16 days ago by Mensur Dlakic6.0k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1366 users visited in the last hour