0
0
SciPydata~5 mins

Converting between formats in SciPy

Choose your learning style9 modes available
Introduction

We convert data between formats to use it in different tools or save it efficiently.

You want to save a sparse matrix in a smaller file to save space.
You need to change data format to use a specific function that accepts only one format.
You want to speed up calculations by using a format optimized for certain operations.
You want to share data with others who use different software requiring a specific format.
Syntax
SciPy
new_matrix = old_matrix.toformat()

Replace toformat() with the desired format method like tocsc(), tocsr(), tolil(), etc.

The original matrix stays the same; a new converted matrix is returned.

Examples
Convert a CSR matrix to CSC format.
SciPy
from scipy.sparse import csr_matrix

csr = csr_matrix([[0, 0, 1], [1, 0, 0]])
csc = csr.tocsc()
Convert a CSC matrix to LIL format.
SciPy
from scipy.sparse import csc_matrix

csc = csc_matrix([[0, 2], [3, 0]])
lil = csc.tolil()
Convert a LIL matrix to CSR format after adding data.
SciPy
from scipy.sparse import lil_matrix

lil = lil_matrix((3, 3))
lil[0, 0] = 5
csr = lil.tocsr()
Sample Program

This code creates a sparse matrix in CSR format, converts it to CSC, then to LIL format, and prints all as dense arrays to show they hold the same data.

SciPy
from scipy.sparse import csr_matrix

# Create a CSR sparse matrix
csr = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]])

# Convert CSR to CSC format
csc = csr.tocsc()

# Convert CSC to LIL format
lil = csc.tolil()

# Print all formats to see differences
print('CSR format:\n', csr.toarray())
print('CSC format:\n', csc.toarray())
print('LIL format:\n', lil.toarray())
OutputSuccess
Important Notes

Different sparse formats are better for different tasks: CSR is good for row slicing, CSC for column slicing, and LIL for incremental construction.

Converting formats can take time and memory, so do it only when needed.

Summary

Use toformat() methods to convert sparse matrices between formats.

Conversion helps use the right format for your task or tool.

Always check the data after conversion to ensure it stayed the same.