Skip to content

Instantly share code, notes, and snippets.

@jlaw9
Forked from vtraag/permute_sparse_matrix.py
Last active November 13, 2020 20:42
Show Gist options
  • Save jlaw9/cf546dc10f25424e5f5422428beeae88 to your computer and use it in GitHub Desktop.
Save jlaw9/cf546dc10f25424e5f5422428beeae88 to your computer and use it in GitHub Desktop.
Permute sparse matrix in Python using scipy COO format
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