0
votes

I am trying to create a sparse matrix by reading the documentation.

So, according to the documentation (https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html):

enter image description here

When I try:

csr_matrix((data = np.array([1, 1, 1, 1, 1, 1]), indices = np.array(2, 3, 4, 5, 7, 7), indptr = np.array([0, 1, 2, 3, 2, 1])))

I get an exception:

File "", line 1 csr_matrix((data = np.array([1, 1, 1, 1, 1, 1]), indices = np.array(2, 3, 4, 5, 7, 7), indptr = np.array([0, 1, 2, 3, 2, 1]))) ^ SyntaxError: invalid syntax

When I try:

csr_matrix((np.array([1, 1, 1, 1, 1, 1]), np.array(2, 3, 4, 5, 7, 7), np.array([0, 1, 2, 3, 2, 1])))

again an error message results:

ValueError: only 2 non-keyword arguments accepted

My intention here is to create a matrix which has ones in the columns with indexes
2, 3, 4, 5, 7, 7
where the corresponding rows have indexes
0, 1, 2, 3, 2, 1

(i.e., (0, 2) , (1, 3) , (2, 4) etc).

1
The first uses assignment not allowed. The second has missing brackets inside numpy's constructor (np.array(1,2,3) is not going to work). Grab the docs of all the functions involved, including np.array(). - sascha
Pay close attention to the use of (). - hpaulj
Yes you are right, it was a typo after all. - user8270077

1 Answers

0
votes

You should be all set with

from scipy.sparse import csr_matrix
import numpy as np

my_csr = csr_matrix((np.array([1,1,1,1,1,1]), (np.array([0, 1, 2, 3, 2, 1]), np.array([2, 3, 4, 5, 7, 7]))), shape = (8,8))

Note that you need to specify the shape of the matrix (here I set the matrix to be a square 8x8 matrix via the parameter shape). Note also the order of the arrays and the use of round brackets!

You can verify that this is satisfactory by converting to a dense format:

my_csr.toarray()