Home > database >  Shuffle a numpy array with the largest element at the beginning in Python
Shuffle a numpy array with the largest element at the beginning in Python

Time:07-05

I am trying to shuffle the array r1 such that the largest element is always at r2[0,0]. The current and one possible expected output is attached.

import numpy as np
r1 = np.array([[150.        , 132.5001244 , 115.00024881],
       [ 97.50037321,  80.00049761,  62.50062201],
       [ 45.00074642,  27.50087082,  10.00099522]])
r2=np.random.shuffle(r1)
print("r2 =",r2)

The current output is

r2 = None

One possible expected output is

array([[150.,62.50062201,115.00024881],  
       [27.50087082,80.00049761,132.5001244]
       [10.00099522,97.50037321,45.00074642]])

CodePudding user response:

For clarity, here is how you should proceed:

import numpy as np

r1 = np.array([[150.        , 132.5001244 , 115.00024881],
               [ 97.50037321,  80.00049761,  62.50062201],
               [ 45.00074642,  27.50087082,  10.00099522]])

# make a copy and shuffle the copy
r2 = r1.copy()
np.random.shuffle(r2.ravel())

# get the index of the max
idx = np.unravel_index(r2.argmax(), r2.shape)

# swap first and max
r2[idx], r2[(0, 0)] = r2[(0, 0)], r2[idx]

print(r2)

Alternative

If the the array is initially sorted, we can use a flat view of the array:

r1 = np.array([[150.        , 132.5001244 , 115.00024881],
               [ 97.50037321,  80.00049761,  62.50062201],
               [ 45.00074642,  27.50087082,  10.00099522]])

r2 = r1.copy()

# r2.ravel() returns a view of the original array
# so we can shuffle only the items starting from 1
np.random.shuffle(r2.ravel()[1:])

possible output:

[[150.          80.00049761  62.50062201]
 [ 97.50037321 132.5001244  115.00024881]
 [ 45.00074642  27.50087082  10.00099522]]
  • Related