2

Given a 2D array, I would like to permute this array row-wise.

Currently, I will create a for loop to permute the 2D array row by row as below:

for i in range(npart):
    pr=np.random.permutation(range(m))
    # arr_rand3 is the same as arr, but with each row permuted
    arr_rand3[i,:]=arr[i,pr]

But, I wonder whether there is some setting within Numpy that can perform this in single line (without the for-loop).

The full code is

import numpy as np

arr=np.array([[0,0,0,0,0],[0,4,1,1,1],[0,1,1,2,2],[0,3,2,2,2]])
npart=len(arr[:,0])
m=len(arr[0,:])
# Permuted version of arr
arr_rand3=np.zeros(shape=np.shape(arr),dtype=np.int)
# Nodal association matrix for C
X=np.zeros(shape=(m,m),dtype=np.double)
# Random nodal association matrix for C_rand3
X_rand3=np.zeros(shape=(m,m),dtype=np.double)
  
for i in range(npart):
    pr=np.random.permutation(range(m))
    # arr_rand3 is the same as arr, but with each row permuted
    arr_rand3[i,:]=arr[i,pr]
2
  • What numpy version are you using? Commented Sep 29, 2021 at 15:26
  • Thanks for interest in this OP, Im using numpy==1.19.5 Commented Sep 29, 2021 at 15:27

1 Answer 1

3

In Numpy 1.19+ you should be able to do:

import numpy as np

arr = np.array([[0, 0, 0, 0, 0], [0, 4, 1, 1, 1], [0, 1, 1, 2, 2], [0, 3, 2, 2, 2]])

rng = np.random.default_rng()
arr_rand3 = rng.permutation(arr, axis=1)

print(arr_rand3)

Output

[[0 0 0 0 0]
 [4 0 1 1 1]
 [1 0 1 2 2]
 [3 0 2 2 2]]

According to the documentation, the method random.Generator.permutation receives a new parameter axis:

axis int, optional
The axis which x is shuffled along. Default is 0.

Sign up to request clarification or add additional context in comments.

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.