Shuffle columns of an array with Numpy

Viewed 26820

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]])
6 Answers
>>> print(s0)
>>> [[0. 1. 0. 1.]
     [0. 1. 0. 0.]
     [0. 1. 0. 1.]
     [0. 0. 0. 1.]]
>>> print(np.random.permutation(s0.T).T)
>>> [[1. 0. 1. 0.]
     [0. 0. 1. 0.]
     [1. 0. 1. 0.]
     [1. 0. 0. 0.]]

np.random.permutation(), does the row permutation.

There is another way, which does not use transposition and is apparently faster:

np.take(r, np.random.permutation(r.shape[1]), axis=1, out=r)

CPU times: user 1.14 ms, sys: 1.03 ms, total: 2.17 ms. Wall time: 3.89 ms

The approach in other answers: np.random.shuffle(r.T)

CPU times: user 2.24 ms, sys: 0 ns, total: 2.24 ms Wall time: 5.08 ms

I used r = np.arange(64*1000).reshape(64, 1000) as an input.

Related