Complete the code to create a CSR matrix from data, row indices, and column indices.
from scipy.sparse import csr_matrix data = [1, 2, 3] rows = [0, 0, 1] cols = [0, 2, 1] matrix = csr_matrix(([1], (rows, cols)), shape=(2, 3)) print(matrix.toarray())
The first argument to csr_matrix is the data values, so we use data.
Complete the code to get the number of non-zero elements in the CSR matrix.
from scipy.sparse import csr_matrix matrix = csr_matrix([[0, 0, 1], [2, 0, 3]]) non_zero_count = matrix.[1] print(non_zero_count)
shape or size which give matrix dimensions, not count of non-zero elements.The nnz attribute gives the number of non-zero elements in a CSR matrix.
Fix the error in the code to convert a dense numpy array to CSR format.
import numpy as np from scipy.sparse import csr_matrix arr = np.array([[0, 4, 0], [3, 0, 0]]) csr = csr_matrix([1]) print(csr.toarray())
The csr_matrix constructor accepts a numpy array directly to convert it to CSR format.
Fill both blanks to create a CSR matrix and then access its data array.
from scipy.sparse import csr_matrix data = [10, 20, 30] rows = [0, 1, 2] cols = [1, 2, 0] matrix = csr_matrix(([1], (rows, cols)), shape=(3, 3)) data_array = matrix.[2] print(data_array)
The first blank is the data values to build the matrix. The second blank accesses the data attribute of the CSR matrix which stores non-zero values.
Fill all three blanks to create a CSR matrix, convert it to dense, and get its shape.
from scipy.sparse import csr_matrix data = [5, 8, 3, 6] rows = [0, 0, 1, 2] cols = [0, 2, 2, 1] matrix = csr_matrix(([1], ([2], [3])), shape=(3, 3)) dense = matrix.toarray() print(dense) print(matrix.shape)
The first blank is the data values, the second is the row indices, and the third is the column indices to build the CSR matrix.