Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Search Elements in a Matrix - Python
Next article icon

How to Create a Sparse Matrix in Python

Last Updated : 18 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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]]  


Next Article
Search Elements in a Matrix - Python

A

AmiyaRanjanRout
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

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 indi
    2 min read
  • Search Elements in a Matrix - Python
    The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
    3 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?
    Our task is to create an array of zeros in Python. This can be achieved using various methods, such as numpy.zeros(), which is efficient for handling large datasets. Other different methods are: Using the In-Build method numpy.zeros() methodUsing simple multiplication Using List comprehensionUsing i
    5 min read
  • Summation Matrix columns - Python
    The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
    2 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
  • Python - Convert Matrix to Dictionary
    The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
    4 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
  • Python - Sort Matrix by None frequency
    In the world of Python programming, many developers aim to make matrix operations efficient and elegant in their code. A fascinating challenge that comes up is sorting a matrix based on how often the mysterious "None" element appears, adding an interesting twist to data manipulation in Python. Given
    9 min read
  • Python - Create List of Size n
    Creating a list of size n in Python can be done in several ways. The easiest and most efficient way to create a list of size n is by multiplying a list. This method works well if we want to fill the list with a default value, like 0 or None. [GFGTABS] Python # Size of the list n = 5 # Creating a lis
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences