Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle columns of an array with Numpy

Tags:

Let's say I have an array r of dimension (n, m). I would like to shuffle the columns of that array.

If I use numpy.random.shuffle(r) it shuffles the lines. How can I only shuffle the columns? So that the first column become the second one and the third the first, etc, randomly.

Example:

input:

array([[  1,  20, 100],        [  2,  31, 401],        [  8,  11, 108]]) 

output:

array([[  20, 1, 100],        [  31, 2, 401],        [  11,  8, 108]]) 
like image 383
Maxime Chéramy Avatar asked Dec 12 '13 14:12

Maxime Chéramy


People also ask

How do I shuffle dataset using Numpy?

With the help of numpy. random. shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly. Return : Return the reshuffled numpy array.

Can you shuffle an array in Python?

Also, Using numpy. random. shuffle() function, we can shuffle the multidimensional array.

How does Numpy shuffle work?

Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.


1 Answers

One approach is to shuffle the transposed array:

 np.random.shuffle(np.transpose(r)) 

Another approach (see YXD's answer https://stackoverflow.com/a/20546567/1787973) is to generate a list of permutations to retrieve the columns in that order:

 r = r[:, np.random.permutation(r.shape[1])] 

Performance-wise, the second approach is faster.

like image 138
Maxime Chéramy Avatar answered Sep 22 '22 01:09

Maxime Chéramy