0
0
SciPydata~5 mins

COO format (Coordinate) in SciPy

Choose your learning style9 modes available
Introduction

COO format helps store sparse data efficiently by saving only the positions and values of non-zero elements.

When you have a large matrix with mostly zeros and want to save memory.
When you want to quickly create a sparse matrix from lists of row, column, and data values.
When you need to perform operations on sparse matrices without converting to dense format.
When you want to store graph edges as coordinates for network analysis.
Syntax
SciPy
scipy.sparse.coo_matrix((data, (row, col)), shape=(M, N))

data is a list or array of non-zero values.

row and col are lists or arrays of the same length as data, indicating positions.

Examples
This creates a 3x3 sparse matrix with values 4, 5, 7 at positions (0,1), (1,2), and (2,0).
SciPy
from scipy.sparse import coo_matrix

row = [0, 1, 2]
col = [1, 2, 0]
data = [4, 5, 7]
sparse_matrix = coo_matrix((data, (row, col)), shape=(3, 3))
print(sparse_matrix.toarray())
A 2x3 matrix with values placed at specified coordinates.
SciPy
from scipy.sparse import coo_matrix

row = [0, 0, 1]
col = [0, 2, 1]
data = [1, 2, 3]
sparse_matrix = coo_matrix((data, (row, col)), shape=(2, 3))
print(sparse_matrix.toarray())
Sample Program

This program creates a 4x4 sparse matrix with four non-zero values at given coordinates and prints the full matrix.

SciPy
from scipy.sparse import coo_matrix

# Define the positions and values of non-zero elements
row = [0, 2, 2, 3]
col = [0, 1, 3, 0]
data = [10, 20, 30, 40]

# Create a 4x4 sparse matrix in COO format
sparse = coo_matrix((data, (row, col)), shape=(4, 4))

# Print the dense form of the sparse matrix
print(sparse.toarray())
OutputSuccess
Important Notes

COO format is good for constructing sparse matrices but slower for arithmetic operations compared to CSR or CSC formats.

Rows and columns indices start at 0.

Summary

COO format stores only non-zero values and their row and column positions.

It is useful for creating sparse matrices from coordinate data.

Use toarray() to see the full dense matrix.