from scipy.sparse import csc_matrix import numpy as np matrix = np.array([[0, 0, 1], [2, 0, 0], [0, 3, 4]]) csc = csc_matrix(matrix) print(csc.data) print(csc.indices) print(csc.indptr)
The CSC format stores non-zero values column by column. The data array holds these values in order. The indices array holds the row indices of each data element. The indptr array points to column start positions in data.
For the given matrix:
[[0, 0, 1], [2, 0, 0], [0, 3, 4]]
Column 0 has non-zero value 2 at row 1.
Column 1 has non-zero value 3 at row 2.
Column 2 has non-zero values 1 at row 0 and 4 at row 2.
So data = [1, 2, 3, 4] is incorrect order; correct order is [2, 3, 1, 4] which matches option A.
from scipy.sparse import csc_matrix import numpy as np matrix = np.array([[0, 5, 0], [0, 0, 0], [7, 0, 9]]) csc = csc_matrix(matrix) print(csc.nnz)
The matrix has three non-zero values: 5, 7, and 9.
So the number of non-zero elements (nnz) is 3.
from scipy.sparse import csc_matrix import numpy as np data = np.array([1, 2, 3]) indices = np.array([0, 1, 2]) indptr = np.array([0, 1, 2, 3]) csc = csc_matrix((data, indices, indptr), shape=(3, 3))
The CSC matrix constructor expects a tuple of (data, indices, indptr) in that order.
Option A swaps indptr and indices, causing a ValueError.
Option A misses indptr, causing a TypeError.
Option A has a shape mismatch causing a ValueError.
from scipy.sparse import csc_matrix import numpy as np matrix = np.array([[0, 1, 0], [2, 0, 3], [0, 4, 0]]) csc = csc_matrix(matrix)
getcol(1) extracts the second column (index 1) as a sparse matrix.
Calling toarray() converts it to a dense 2D array.
flatten() converts it to 1D array.
Option B returns a 2D array but is valid too, but option B matches the exact requested output (1D array).
Options A and C extract rows, not columns.
CSC format stores non-zero elements column by column, so accessing a column is direct and efficient.
CSR stores data row by row, so extracting a column requires scanning multiple rows, which is slower.
Therefore, CSC is more efficient for column slicing.