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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With