-
-
Save jlaw9/cf546dc10f25424e5f5422428beeae88 to your computer and use it in GitHub Desktop.
Permute sparse matrix in Python using scipy COO format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy import sparse | |
def permute_sparse_matrix(M, row_order=None, col_order=None): | |
""" | |
Reorders the rows and/or columns in a scipy sparse matrix to the specified order. | |
""" | |
if row_order is None and col_order is None: | |
return M | |
new_M = M | |
if row_order is not None: | |
I = sparse.eye(M.shape[0]).tocoo() | |
I.row = I.row[row_order] | |
new_M = I.dot(new_M) | |
if col_order is not None: | |
I = sparse.eye(M.shape[1]).tocoo() | |
I.col = I.col[col_order] | |
new_M = new_M.dot(I) | |
return new_M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment