Merge Scipy:稀疏布尔矩阵的并集
在Scipy中,获得多个布尔稀疏(Merge Scipy:稀疏布尔矩阵的并集,merge,scipy,boolean,sparse-matrix,Merge,Scipy,Boolean,Sparse Matrix,在Scipy中,获得多个布尔稀疏(csr)矩阵的并集A+B+C(具有相同形状)的最有效方法是什么 联合除其他外意味着: 稀疏变化 重叠是可能的 只需添加它们: import scipy.sparse as sparse x = sparse.csr_matrix([[True, True, False], [False, False, False], [True, False, False]] , dtype=bool) y = sparse.csr_matrix([[False, True,
csr
)矩阵的并集A+B+C
(具有相同形状)的最有效方法是什么
联合除其他外意味着:
- 稀疏变化
- 重叠是可能的
import scipy.sparse as sparse
x = sparse.csr_matrix([[True, True, False], [False, False, False], [True, False, False]] , dtype=bool)
y = sparse.csr_matrix([[False, True, False], [False, True, False], [False, True, False]], dtype=bool)
print((x + y).todense())
>>[[ True True False]
[False True False]
[ True True False]]
编辑
如果您想直接访问索引,可以使用coo
格式(允许检索行和列索引),堆叠索引并使用np.unique
(免责声明:我没有检查效率比较):
改变csr_矩阵的稀疏结构是低效的。我想知道是否可以在后台快速合并数据(即数据、索引、indptr)。我添加了一种在后台获取索引并使用它们的方法:
coo
format允许这样做。注意:也许你能找到更有效的方法(我也没有尝试过速度比较)。
import scipy.sparse as sparse
c2=sparse.eye(5, k=1, dtype=bool, format='coo')
c1=sparse.eye(5, dtype=bool, format='coo')
c3 = c1.copy()
c3.row, c3.col = np.unique(np.hstack((np.vstack((c1.col, c1.row)),np.vstack((c2.col, c2.row)))), axis=1)
c3.data = np.ones(c3.row.size, dtype=bool)
c3.todense()
>> matrix([[ True, False, False, False, False],
[ True, True, False, False, False],
[False, True, True, False, False],
[False, False, True, True, False],
[False, False, False, True, True]])