Home > database >  Efficiently permute array in row wise using Numpy
Efficiently permute array in row wise using Numpy

Time:09-30

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]

CodePudding user response:

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.

  • Related