我有兩個數組A和B.在NumPy中,您可以使用A作爲B的索引。如何使用SciPy CSR Sparse Arrays將一個陣列與另一個陣列進行索引?
A = np.array([[1,2,3,1,7,3,1,2,3],[4,5,6,4,5,6,4,5,6],[7,8,9,7,8,9,7,8,9]])
B= np.array([1,2,3,4,5,6,7,8,9,0])
c = B[A]
主要生產:
[[2 3 4 2 8 4 2 3 4] [5 6 7 5 6 7 5 6 7] [8 9 0 8 9 0 8 9 0]]
然而,在我的情況陣列A和B是SciPy的CSR稀疏數組,他們似乎並不支持索引。
A_sparse = sparse.csr_matrix(A)
B_sparse = sparse.csr_matrix(B)
c = B_sparse[A_sparse]
這導致:我想出了下面的功能來複制與稀疏矩陣NumPy的行爲
IndexError: Indexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.
:
def index_sparse(A,B):
A_sparse = scipy.sparse.coo_matrix(A)
B_sparse = sparse.csr_matrix(B)
res = sparse.csr_matrix(A_sparse)
for i,j,v in zip(A_sparse.row, A_sparse.col, A_sparse.data):
res[i,j] = B_sparse[0, v]
return res
res = index_sparse(A, B)
print res.todense()
循環數組和具有與以在Python中創建一個新數組並不理想。使用SciPy/NumPy的內置函數是否有更好的方法?