Copy numpy array values ​​to a specific place in a sparse matrix

So, I'm trying to copy values ​​from one numpy array to a sparse matrix. The first array is as follows:

results_array = [[ 3.00000000e+00 1.00000000e+00 4.00000000e+00 1.00000000e+03] [ 6.00000000e+00 2.00000000e+00 5.00000000e+00 7.00000000e+02] [ 1.60000000e+01 4.00000000e+00 8.00000000e+00 1.00000000e+03]} 

The second value (or results_array[i][1] ) defines the column identifier, the third value ( results_array[i][2] ) defines the row identifier, and the fourth value ( results_array[i][3] ) defines the value of this row, a pair of columns .

So far I have the following:

 for i in result_array: sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14)) print "last array", sparse_matrix 

The output I get is:

 File "C:/Users/Andrew/Google Drive/Uni/Final Year/Research Project/Programming/Mine/First UEA/xl_optim/Runestone 2.py", line 13, in <module> sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14)) File "C:\Users\Andrew\Anaconda2\lib\site-packages\scipy\sparse\compressed.py", line 48, in __init__ other = self.__class__(coo_matrix(arg1, shape=shape)) File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 182, in __init__ self._check() File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 219, in _check nnz = self.nnz File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 194, in getnnz nnz = len(self.data) TypeError: len() of unsized object 

It seems to me that I need to create a sparse matrix first and then add the values ​​to it iteratively (I represent something like .append , but in a specific place in the matrix), but I have no idea how to create an empty sparse matrix, and then assign her meanings.

Let me know if you need further clarification. Thanks!

0
source share
1 answer

The first element in the tuple that you pass to csc_matrix must be a vector of values, while you pass it an integer. More fundamentally, you try to call the csc_matrix constructor several times in a loop so that it overwrites sparse_matrix at each iteration.

You want to call csc_matrix once with a vector for each parameter, for example:

 values = results_array[:, 3] row_idx = results_array[:, 2] col_idx = results_array[:, 1] sparse_array = csc_matrix((values, (row_idx, col_idx)), shape=(14, 14)) 
+3
source

All Articles