How to check sparse matrix in python

I have a matrix and I want to check if it is sparse or not.

Things I have tried:

  1. isinstance method:

    if isinstance(, scipy.sparse.csc.csc_matrix):
    

This works fine if I know exactly which sparse class I want to check.

  1. getformat method: But it assumes that my matrix is sparse and give format

But I want a way to know if matrix is sparse or not, and should work irrespective of which sparse class.

Kindly help me.

asked Mar 8, 2016 at 18:06

scipy.sparse.issparse(my_matrix)

answered Mar 8, 2016 at 18:44

BoaBoa

2,5341 gold badge21 silver badges37 bronze badges

You can do sparsity = 1.0 - count_nonzero(X) / X.size

This works for any matrices.

answered Mar 16, 2020 at 3:50

Not the answer you're looking for? Browse other questions tagged python class matrix sparse-matrix or ask your own question.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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 elements in the matrix,

    Examples: 

    Input : 1 0 3
            0 0 4
            6 0 0
    Output : Yes
    There are 5 zeros. This count
    is more than half of matrix
    size.
    
    Input : 1 2 3
            0 7 8
            5 0 7 
    Output: No 

    To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. 

    Implementation:

    C++

    #include

    using namespace std;

    const int MAX = 100;

    bool isSparse(int array[][MAX], int m, int n)

    {

        int counter = 0;

        for (int i = 0; i < m; ++i)

            for (int j = 0; j < n; ++j)

                if (array[i][j] == 0)

                    ++counter;

        return (counter > ((m * n) / 2));

    }

    int main()

    {

        int array[][MAX] = { { 1, 0, 3 },

                            { 0, 0, 4 },

                            { 6, 0, 0 } };

        int m = 3,

            n = 3;

        if (isSparse(array, m, n))

            cout << "Yes";

        else

            cout << "No";

    }

    Java

    import java.io.*;

    class GFG {

        static int MAX = 100;

        static boolean isSparse(int array[][], int m, int n)

        {

            int counter = 0;

            for (int i = 0; i < m; ++i)

                for (int j = 0; j < n; ++j)

                    if (array[i][j] == 0)

                        ++counter;

            return (counter > ((m * n) / 2));

        }

        public static void main(String args[])

        {

            int array[][] = { { 1, 0, 3 },

                                { 0, 0, 4 },

                                { 6, 0, 0 } };

            int m = 3,

                n = 3;

            if (isSparse(array, m, n))

                System.out.println("Yes");

            else

                System.out.println("No");

        }

    }

    Python3

    MAX = 100

    def isSparse(array,m, n) :

        counter = 0

        for i in range(0,m) :

            for j in range(0,n) :

                if (array[i][j] == 0) :

                    counter = counter + 1

        return (counter >

                ((m * n) // 2))

    array = [ [ 1, 0, 3 ],

              [ 0, 0, 4 ],

              [ 6, 0, 0 ] ]

    m = 3

    n = 3

    if (isSparse(array, m, n)) :

        print("Yes")

    else :

        print("No")

    C#

    using System;

    class GFG {

        static bool isSparse(int [,]array, int m,

                                           int n)

        {

            int counter = 0;

            for (int i = 0; i < m; ++i)

                for (int j = 0; j < n; ++j)

                    if (array[i,j] == 0)

                        ++counter;

            return (counter > ((m * n) / 2));

        }

        public static void Main()

        {

            int [,]array = { { 1, 0, 3 },

                             { 0, 0, 4 },

                             { 6, 0, 0 } };

            int m = 3,

                n = 3;

            if (isSparse(array, m, n))

                Console.WriteLine("Yes");

            else

                Console.WriteLine("No");

        }

    }

    PHP

    $MAX = 100;

    function isSparse( $array, $m, $n)

    {

        $counter = 0;

        for ($i = 0; $i < $m; ++$i)

            for ($j = 0; $j < $n; ++$j)

                if ($array[$i][$j] == 0)

                    ++$counter;

        return ($counter > (($m * $n) / 2));

    }

        $array = array(array(1, 0, 3),

                       array(0, 0, 4),

                       array(6, 0, 0));

        $m = 3;

        $n = 3;

        if (isSparse($array, $m, $n))

            echo "Yes";

        else

            echo "No";

    ?>

    Javascript

    Time Complexity: O(m*n) 
    Auxiliary Space: O(1)

    This article is contributed by Aarti_Rathi and Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.


    How do you check if a matrix is sparse or not?

    The definition of a sparse matrix is, if the 2/3rd of the elements are 0, then the matrix is denoted as a sparse matrix. Here is the example of a sparse matrix. To check it, we will count the number of 0s in the matrix, then if that count is greater than 2/3rd of the total elements, then this is sparse.

    How do you find the sparsity of a matrix?

    The number of zero-valued elements divided by the total number of elements (e.g., m × n for an m × n matrix) is called the sparsity of the matrix (which is equal to 1 minus the density of the matrix).

    How do you sparse a matrix in python?

    Sparse matrices in Python.
    import numpy as np..
    from scipy. sparse import csr_matrix..
    # create a 2-D representation of the matrix..
    A = np. array([[1, 0, 0, 0, 0, 0], [0, 0, 2, 0, 0, 1],\.
    [0, 0, 0, 2, 0, 0]]).
    print("Dense matrix representation: \n", A).

    What does SciPy sparse Csr_matrix do?

    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.