Puckl
Puckl

Reputation: 741

Randomly shuffle a sparse matrix in python

is there an easy way to shuffle a sparse matrix in python?

This is how I shuffle a non-sparse matrix:

    index = np.arange(np.shape(matrix)[0])
    np.random.shuffle(index)
    return matrix[index]

How can I do it with numpy sparse?

Upvotes: 11

Views: 7034

Answers (3)

Anurag Pandey
Anurag Pandey

Reputation: 1

A better way can be shuffling the index of CSR Matrix and fetching the rows of matrix as such:

from random import shuffle
indices = np.arange(matrix.shape[0]) #gets the number of rows 
shuffle(indices)
shuffled_matrix = matrix[list(indices)] 

Upvotes: 0

shaneb
shaneb

Reputation: 1474

In case anyone is looking to randomly get a subsample of rows from a sparse matrix, this related post may also be useful: How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list

Upvotes: 1

Puckl
Puckl

Reputation: 741

Ok, found it. The sparse format looks a bit confusing in the print-out.

    index = np.arange(np.shape(matrix)[0])
    print index
    np.random.shuffle(index)
    return matrix[index, :]

Upvotes: 18

Related Questions