Skip to content

Instantly share code, notes, and snippets.

@drmingle
Created June 7, 2018 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmingle/4883d2f368277abd37c01d0b36652b5d to your computer and use it in GitHub Desktop.
Save drmingle/4883d2f368277abd37c01d0b36652b5d to your computer and use it in GitHub Desktop.
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