jdoe
jdoe

Reputation: 654

Create 2 matrices based on list of index value

I have a scipy sparse matrix - title - and a python list index. The list contains integers which correspond to rows in the title matrix. From this I wish to create 2 new scipy sparse matrices:

Eg.

import numpy as np
from scipy import sparse
titles = sparse.csr_matrix(np.ones((5,5)))
index = [3,2]

Where the desired output for print(matrix1.todense()) is:

[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]

and the desired output for print(matrix2.todense()) is:

[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]

Upvotes: 0

Views: 39

Answers (1)

cs95
cs95

Reputation: 402493

You can use np.setdiff1d to find exclusive indices and just index titles appropriately.

idx1 = [3, 2]
idx2 = np.setdiff1d(np.arange(titles.shape[0]), idx1)

matrix1 = titles[idx2].todense()
matrix2 = titles[idx1].todense()

print(matrix1)
[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]

print(matrix2)
[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]

Upvotes: 1

Related Questions