Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix certain elements and shuffle the rest in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ]])

>Solution :

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 ]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading