1

There is a way to randomly permute the columns of a matrix? I tried to use np.random.permutation but the obtained result is not what i need. What i would like to obtain is to change randomly the position of the columns of the matrix, without to change the position of the values of each columns.

Es.

starting matrix:

1   6   11  16
2   7   12  17
3   8   13  18
4   9   14  19
5   10  15  20

Resulting matrix

11  7   1  16
12  8   2  17
13  9   3  18
14  10  4  19
15  11  5  20
L3viathan
  • 26,748
  • 2
  • 58
  • 81
vittorio
  • 143
  • 3
  • 14

1 Answers1

4

You could shuffle the transposed array:

q = np.array([1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20])
q = q.reshape((5,4))

print(q)
# [[ 1  6 11 16]
# [ 2  7 12 17]
# [ 3  8 13 18]
# [ 4  9 14 19]
# [ 5 10 15 20]]    
np.random.shuffle(np.transpose(q))

print(q)
# [[ 1 16  6 11]
# [ 2 17  7 12]
# [ 3 18  8 13]
# [ 4 19  9 14]
# [ 5 20 10 15]]

Another option for general axis is:

q = np.array([1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20])
q = q.reshape((5,4))
q = q[:, np.random.permutation(q.shape[1])]

print(q)
# [[ 6 11 16  1]
# [ 7 12 17  2]
# [ 8 13 18  3]
# [ 9 14 19  4]
# [10 15 20  5]]
David
  • 8,113
  • 2
  • 17
  • 36
  • Clever. That works because `np.transpose` just returns a view into `q`? – L3viathan Mar 20 '20 at 10:52
  • @L3viathan What do you mean by view? – David Mar 20 '20 at 10:55
  • "A [view](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html) is returned whenever possible" — [docs for numpy.transpose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html). Since the return value of np.transpose (usually) doesn't return a new copy but just a view onto the same data, shuffling the transposition has an effect on the previous, underlying array. – L3viathan Mar 20 '20 at 11:46
  • 1
    @L3viathan Exactly, this is why I added the other option using the `np.random.permutation`. – David Mar 20 '20 at 12:00
  • Using random.permutation works fine. Thank you for the suggestion! – vittorio May 08 '20 at 21:32