How to Create a Sparse Matrix in Python
Last Updated :
18 Aug, 2020
If most of the elements of the matrix have 0 value, then it is called a sparse matrix. The two major benefits of using sparse matrix instead of a simple matrix are:
- Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements.
- Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements.
Sparse matrices are generally utilized in applied machine learning such as in data containing data-encodings that map categories to count and also in entire subfields of machine learning such as natural language processing (NLP).
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value).
Create a Sparse Matrix in Python
Python’s SciPy gives tools for creating sparse matrices using multiple data structures, as well as tools for converting a dense matrix to a sparse matrix. The function csr_matrix() is used to create a sparse matrix of compressed sparse row format whereas csc_matrix() is used to create a sparse matrix of compressed sparse column format.
# Using csr_matrix()
Syntax:
scipy.sparse.csr_matrix(shape=None, dtype=None)
Parameters:
shape: Get shape of a matrix
dtype: Data type of the matrix
Example 1:
Python
# Python program to create
# sparse matrix using csr_matrix()
# Import required package
import numpy as np
from scipy.sparse import csr_matrix
# Creating a 3 * 4 sparse matrix
sparseMatrix = csr_matrix((3, 4),
dtype = np.int8).toarray()
# Print the sparse matrix
print(sparseMatrix)
Output:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
Example 2:
Python
# Python program to create
# sparse matrix using csr_matrix()
# Import required package
import numpy as np
from scipy.sparse import csr_matrix
row = np.array([0, 0, 1, 1, 2, 1])
col = np.array([0, 1, 2, 0, 2, 2])
# taking data
data = np.array([1, 4, 5, 8, 9, 6])
# creating sparse matrix
sparseMatrix = csr_matrix((data, (row, col)),
shape = (3, 3)).toarray()
# print the sparse matrix
print(sparseMatrix)
Output:
[[ 1 4 0]
[ 8 0 11]
[ 0 0 9]]
# Using csc_matrix()
Syntax:
scipy.sparse.csc_matrix(shape=None, dtype=None)
Parameters:
shape: Get shape of a matrix
dtype: Data type of the matrix
Example 1:
Python
# Python program to create
# sparse matrix using csc_matrix()
# Import required package
import numpy as np
from scipy.sparse import csc_matrix
# Creating a 3 * 4 sparse matrix
sparseMatrix = csc_matrix((3, 4),
dtype = np.int8).toarray()
# Print the sparse matrix
print(sparseMatrix)
Output:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
Example 2:
Python
# Python program to create
# sparse matrix using csc_matrix()
# Import required package
import numpy as np
from scipy.sparse import csc_matrix
row = np.array([0, 0, 1, 1, 2, 1])
col = np.array([0, 1, 2, 0, 2, 2])
# taking data
data = np.array([1, 4, 5, 8, 9, 6])
# creating sparse matrix
sparseMatrix = csc_matrix((data, (row, col)),
shape = (3, 3)).toarray()
# print the sparse matrix
print(sparseMatrix)
Output:
[[ 1 4 0]
[ 8 0 11]
[ 0 0 9]]
Similar Reads
Python program to Convert a Matrix to Sparse Matrix Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory.Using a DictionaryConverting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indic
2 min read
Python Program to Check if a given matrix is sparse or not A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elem
4 min read
How to create an array of zeros in Python? Creating an array of zeros in Python involves generating a collection filled entirely with zero values. For example, if we need to create a list of 5 zeros, the list would look like [0, 0, 0, 0, 0]. Letâs explore some common approaches to create zero-filled arrays.Using numpy.zeros()numpy.zeros() cr
4 min read
Python - Matrix creation of n*n Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Take Matrix input from user in Python Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
5 min read