Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
title author date
Create a Sparse Matrix
Damian Mingle
06/07/2018

Preliminaries

# Bring in libraries
import numpy as np
from scipy import sparse

Generate Dense Matrix

# Dense matrix
matrix_dense = np.array([[0, 0],
                   [0, 1],
                   [3, 0]])

Adapt To Sparse Matrix

# Make a compressed sparse row matrix
matrix_sparse = sparse.csr_matrix(matrix_dense)
# Show the sparse matrix

print(matrix_sparse)
matrix_sparse
  (1, 1)	1
  (2, 0)	3





<3x2 sparse matrix of type '<class 'numpy.int32'>'
	with 2 stored elements in Compressed Sparse Row format>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment