+1 vote
in Programming Languages by (66.2k points)

I created a CSR matrix using the csr_array() module of scipy.sparse

from scipy.sparse import csr_array

data = np.array([1, 0, 2, 0, 3, 4, 0, 5, 6])

indices = np.array([0, 2, 0, 2, 3, 4, 3, 4, 5])

indptr = np.array([0, 2, 4, 6, 9])

x = csr_array((data, indices, indptr), shape=(4, 6))

 When I try to select a record using its index (e.g. x[1]), it gives the following error: NotImplementedError: We have not yet implemented 1D sparse slices; please index using explicit indices, e.g. `x[:, [0]]`

How to fix this error?

1 Answer

+3 votes
by (66.8k points)
selected by
 
Best answer

You are getting this error because the 1D sparse slice is not implemented for csr_array. You need to use csr_matrix to use 1D sparse slices. So, using the csr_matrix() module, convert csr_array to csr_matrix. 

Here is an example:

>>> import numpy as np

>>> from scipy.sparse import csr_array

>>> data = np.array([1, 0, 2, 0, 3, 4, 0, 5, 6])

>>> indices = np.array([0, 2, 0, 2, 3, 4, 3, 4, 5])

>>> indptr = np.array([0, 2, 4, 6, 9])

>>> x = csr_array((data, indices, indptr), shape=(4, 6))

Convert CSR array to CSR matrix:

>>> from scipy.sparse import csr_matrix

>>> x1=csr_matrix(x)

>>> x1.toarray()

array([[1, 0, 0, 0, 0, 0],

       [2, 0, 0, 0, 0, 0],

       [0, 0, 0, 3, 4, 0],

       [0, 0, 0, 0, 5, 6]])

>>> x1[1].toarray()

array([[2, 0, 0, 0, 0, 0]])


...