How to create a sparse Matrix in Python?
0

How to create a sparse Matrix in Python?

This recipe helps you create a sparse Matrix in Python
In [1]:
## How to Create A Sparse Matrix
def Kickstarter_Example_2():
    print()
    print(format('How to Create A Sparse Matrix', '*^50'))

    # Load libraries
    import numpy as np
    from scipy import sparse

    # Create a matrix
    matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
    print()
    print("Original Matrix: \n", matrix)

    # Create sparse matrices
    print()
    print("Sparse Matrices: ")
    print()
    print(sparse.csr_matrix(matrix))
    print()
    print(sparse.bsr_matrix(matrix))
    print()
    print(sparse.coo_matrix(matrix))
    print()
    print(sparse.csc_matrix(matrix))
    print()
    print(sparse.dia_matrix(matrix))
    print()
    print(sparse.dok_matrix(matrix))
    print()
    print(sparse.lil_matrix(matrix))
    print()
Kickstarter_Example_2()
**********How to Create A Sparse Matrix***********

Original Matrix:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Sparse Matrices:

  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (1, 0)	4
  (1, 1)	5
  (1, 2)	6
  (2, 0)	7
  (2, 1)	8
  (2, 2)	9

  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (1, 0)	4
  (1, 1)	5
  (1, 2)	6
  (2, 0)	7
  (2, 1)	8
  (2, 2)	9

  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (1, 0)	4
  (1, 1)	5
  (1, 2)	6
  (2, 0)	7
  (2, 1)	8
  (2, 2)	9

  (0, 0)	1
  (1, 0)	4
  (2, 0)	7
  (0, 1)	2
  (1, 1)	5
  (2, 1)	8
  (0, 2)	3
  (1, 2)	6
  (2, 2)	9

  (2, 0)	7
  (1, 0)	4
  (2, 1)	8
  (0, 0)	1
  (1, 1)	5
  (2, 2)	9
  (0, 1)	2
  (1, 2)	6
  (0, 2)	3

  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (1, 0)	4
  (1, 1)	5
  (1, 2)	6
  (2, 0)	7
  (2, 1)	8
  (2, 2)	9

  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (1, 0)	4
  (1, 1)	5
  (1, 2)	6
  (2, 0)	7
  (2, 1)	8
  (2, 2)	9