Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply same permutation for every row in a 2D numpy array

To permute a 1D array A I know that you can run the following code:

import numpy as np
A = np.random.permutation(A)

I have a 2D array and want to apply exactly the same permutation for every row of the array. Is there any way you can specify the numpy to do that for you?

like image 843
jsguy Avatar asked Sep 17 '25 19:09

jsguy


2 Answers

Generate random permutations for the number of columns in A and index into the columns of A, like so -

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

Sample run -

In [100]: A
Out[100]: 
array([[3, 5, 7, 4, 7],
       [2, 5, 2, 0, 3],
       [1, 4, 3, 8, 8]])

In [101]: A[:,np.random.permutation(A.shape[1])]
Out[101]: 
array([[7, 5, 7, 4, 3],
       [3, 5, 2, 0, 2],
       [8, 4, 3, 8, 1]])
like image 186
Divakar Avatar answered Sep 20 '25 07:09

Divakar


Actually you do not need to do this, from the documentation:

If x is a multi-dimensional array, it is only shuffled along its first index.

So, taking Divakar's array:

a = np.array([
    [3, 5, 7, 4, 7],
    [2, 5, 2, 0, 3],
    [1, 4, 3, 8, 8]
])

you can just do: np.random.permutation(a) and get something like:

array([[2, 5, 2, 0, 3],
       [3, 5, 7, 4, 7],
       [1, 4, 3, 8, 8]])

P.S. if you need to perform column permutations - just do np.random.permutation(a.T).T. Similar things apply to multi-dim arrays.

like image 37
Salvador Dali Avatar answered Sep 20 '25 07:09

Salvador Dali