4

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?

2
  • I am sorry for not being very clear. each row should have the same set of elements as before applying the permutation, however the way you arrange the elements in every row should be the same. So if the element in position 0 goes to position 4, the same should happen for every row. Commented Sep 23, 2015 at 20:32
  • 1
    In other words, you want to permute the columns of A? Commented Sep 23, 2015 at 20:49

3 Answers 3

8

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

your method seems to be changing the values of the rows, for example in the first row before the permutation we do not have a 2, but after that we have a 2. I would like to have some kind of masking that for instance, if an element of the first row that was previously in position 0 after the permutation goes to position 4, then the same should happen for the element that is in position 0 of the second row and all the other rows.
3

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.

Comments

1

It depends what you mean on every row.

If you want to permute all values (regardless of row and column), reshape your array to 1d, permute, reshape back to 2d.

If you want to permutate each row but not shuffle the elements among the different columns you need to loop trough the one axis and call permutation.

for i in range(len(A)):
    A[i] = np.random.permutation(A[i])

It can probably done shorter somehow but that is how it can be done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.