How to save scipy.sparse.csr.csr_matrix as csv or other format to handle it with R?
2
0
Entering edit mode
3.7 years ago
hq.huang11.6 ▴ 10

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?

Python R • 11k views
ADD COMMENT
2
Entering edit mode
3.7 years ago
Mark ★ 1.5k

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 COMMENT
1
Entering edit mode
3.7 years ago
Mensur Dlakic ★ 27k

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 COMMENT

Login before adding your answer.

Traffic: 2309 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6