numpy - 交换行 csr_matrix scipy

标签 numpy scipy

我在 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/

相关文章:

python - 继续运行到 "TypeError: ' numpy.float6 4' object is not callable"

python - 从 NumPy 中的不均匀采样数据生成均匀采样数组

python - 根据numpy数组中一行中的重复值删除列

一定范围内整数的 Python numpy 乘积

python - 使用多个 y 值进行插值

Python - 函数乘法的积分

python - Conda 是否取代了对 virtualenv 的需求?

python - 加速numpy中的数组分析

Python:具有多个条件的 np.where

python - 高效地将 CSV 的最后 'n' 行读入 DataFrame