How to fix certain elements and shuffle the rest in Python

Question:

I want to shuffle all the elements of array r2 by keeping the first and the last element fixed. I am using np.random.shuffle() but it is shuffling all the elements. For instance, when shuffling r2, 54.3817864 should be fixed as first and last element and shuffling should happen for the rest. I present the current and expected outputs.

import numpy as np
r2=np.array([[54.3817864 , 53.42810469, 47.94544424, 53.63511598, 49.59728558,
        49.6935623 , 50.70031442, 52.80854701, 50.18808714, 51.80017684,
        51.85747597, 54.3817864 ]])

np.random.shuffle(r2[0])
print([r2])

The current output is

[array([[53.63511598, 50.70031442, 51.80017684, 54.3817864 , 50.18808714,
        47.94544424, 49.59728558, 53.42810469, 49.6935623 , 51.85747597,
        52.80854701, 54.3817864 ]])]

The expected output is

array([[54.3817864 , 47.94544424, 49.6935623 , 50.70031442,53.42810469,
49.59728558,52.80854701, 50.18808714, 
51.80017684,53.63511598, 51.85747597, 54.3817864 ]])
Asked By: user20032724

||

Answers:

You can try changing the indexing while shuffling… Try this..

import numpy as np
r2=np.array([[54.3817864 , 53.42810469, 47.94544424, 53.63511598, 49.59728558,
    49.6935623 , 50.70031442, 52.80854701, 50.18808714, 51.80017684,
    51.85747597, 54.3817864 ]])
np.random.shuffle(r2[0][1:-1])

Output of r2;

array([[54.3817864 , 47.94544424, 53.63511598, 50.70031442, 53.42810469,
        51.80017684, 49.59728558, 50.18808714, 51.85747597, 52.80854701,
        49.6935623 , 54.3817864 ]])
Answered By: Sachin Kohli

You can use numpy array unpacking:

import numpy as np

r2 = np.array([54.3817864, 53.42810469, 47.94544424, 53.63511598, 49.59728558,
               49.6935623, 50.70031442, 52.80854701, 50.18808714, 51.80017684,
               51.85747597, 54.3817864])
first, *others, last = r2
np.random.shuffle(others)
print(np.concatenate((first, others, last), axis=None))

result:

[54.3817864  49.6935623  49.59728558 51.85747597 47.94544424 53.63511598
 52.80854701 53.42810469 50.18808714 50.70031442 51.80017684 54.3817864 ]
Answered By: Hamid Rasti
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.