Randomly shuffle sparse matrix in python

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

Here's how I shuffle an unsharp matrix:

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

How can I do this with numpy sparse?

+6
source share
3 answers

Ok, found it. The rare format looks a bit confusing in the printout.

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

In case someone is looking for a random selection of rows from a sparse matrix, this related post may also be useful: How can I switch to a subsample from scipy.sparse. csr.csr_matrix and list

0
source

A better way would be to shuffle the CSR matrix index and select the matrix rows as such:

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

All Articles