Slicing a scipy sparse matrix using a boolean mask

2019-06-24 02:03发布

I have encountered a difference in how slicing a scipy sparse matrix works in 0.10.0 and 0.10.1. Consider the following piece of code:

from numpy import array, ravel
from scipy.sparse import csr_matrix

mat = csr_matrix(array([[1, 0, 0], [0,1,0], [1,0,0]]))
desired_cols = ravel(mat.sum(0)) > 0

print mat[:, desired_cols].A

In scipy 0.10.0, I get what I expect to get:

[[1 0]
 [0 1]
 [1 0]]

In 0.10.1 and 0.12.0, I get

[[0 0 1]
 [1 1 0]
 [0 0 1]]

I am not sure if this is a bug or I am doing something wrong. I get the same results using coo_matrix and csc_matrix.

I am trying to remove all rows that sum to 0 from the matrix. I understand that csr_matrix does not support efficient column slicing and I should not being this.

2条回答
手持菜刀,她持情操
2楼-- · 2019-06-24 02:21

Use np.flatnonzero(desired_cols) instead of desired_cols and scipy.sparse will support it. Full matrix API support is unavailable in scipy.sparse and features are gradually being introduced.

查看更多
不美不萌又怎样
3楼-- · 2019-06-24 02:30

What is desired_cols in these cases. In recent scipy (0.13.0) the results match your first one (0.10.0). You may have to dig into the github source for scipy if you want to track down changes this far back in the versions.

查看更多
登录 后发表回答