Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill Scipy Sparse Matrix with Ones

I have a scipy sparse matrix that I would like to replace values with ones:

from scipy import sparse
import numpy as np

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

print sparse.coo_matrix(data)

I see that numpy has a ones_like() function but this didn't solve my problem.

The output should look like:

(0, 0)        1
(0, 1)        1
(0, 2)        1
(0, 4)        1
(1, 0)        1
(1, 3)        1
(1, 4)        1
(2, 4)        1
like image 464
slaw Avatar asked Jan 21 '26 10:01

slaw


1 Answers

The easiest way to do this is to manipulate the sparse matrix representation directly. The way to do that will depend on your choice of representation; for COO format, it'd be

data.data[:] = 1

Note that COO format has a weird feature where it allows duplicate entries. If a COO matrix has two entries at location (1, 1), the above code will set both of those entries to 1, resulting in a single entry of 2 if you convert the matrix to another format. If you want a single entry of 1 instead, you can normalize duplicates first

data.sum_duplicates()
data.data[:] = 1
like image 176
user2357112 supports Monica Avatar answered Jan 22 '26 23:01

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!