我在 scipy 中有一个 256x256 csr_matrix,并且有一个我想要应用的新行顺序的列表。我试过这个:
def HblockDiag(z):
Hz = H(z) # H(z) returns a 256x256 csr_matrix
Hz.indices = idenRows
return Hz
但它不起作用,因为 indices
没有给出每行的索引...执行此操作的最佳方法是什么?
编辑:
def HblockDiag(H, idenRows):
x = H.tocoo()
idenRows = np.asarray(idenRows, dtype=x.row.dtype)
x.row = idenRows[x.row]
H = x.tocsr()
return H
test = sps.csr_matrix([[1,2,4],[6,3,4],[8,5,2]])
print test.toarray()
test = HblockDiag(test, [2,0,1])
print test.toarray()
我得到:
[[1 2 4]
[6 3 4]
[8 5 2]]
[[6 3 4]
[8 5 2]
[1 2 4]]
相反,我想得到:
[[8 5 2]
[1 2 4]
[6 3 4]]
最佳答案
从 CSR 格式转换为 COO 格式。
x = Hz.tocoo()
根据文档字符串,
sparse.coo_matrix.__doc__
,COO 具有“与 CSR/CSC 格式之间的快速转换”。排列 COO 矩阵的行
idenRows = np.argsort(idenRows) x.row = idenRows[x.row]
从 COO 转变回 CSR
Hz = x.tocsr()
例如,
import numpy as np
import scipy.sparse as sps
def HblockDiag(H, idenRows):
x = H.tocoo()
idenRows = np.argsort(idenRows)
idenRows = np.asarray(idenRows, dtype=x.row.dtype)
x.row = idenRows[x.row]
H = x.tocsr()
return H
test = sps.csr_matrix([[1,2,4],[6,3,4],[8,5,2]])
print test.toarray()
# [[1 2 4]
# [6 3 4]
# [8 5 2]]
test = HblockDiag(test, [2,0,1])
print test.toarray()
产量
[[8 5 2]
[1 2 4]
[6 3 4]]
PS。一般情况下,只有当矩阵规模很大时才使用稀疏矩阵。如果形状仅为 (256, 256),尚不清楚为什么要使用稀疏矩阵。此外,矩阵应包含 at least 80% zeros for sparse matrices to pay off .
关于numpy - 交换行 csr_matrix scipy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28334719/