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?

How to save scipy.sparse.csr.csr_matrix as csv or other format to handle it with R?

0

Entering edit mode

11 months 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?

1

Entering edit mode

11 months ago

Mark
▴
900

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

1

Entering edit mode

11 months ago

Mensur Dlakic
★
11k

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.

Similar Posts

Loading Similar Posts

Traffic: 2388 users visited in the last hour

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