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 assign array values to the n-1 location in the array

I have an array like this: [1, 2, 3, 4, 5]. I shuffle it to get this: [1, 5, 4, 2, 3].

The Goal: Assign each value in the array to the n-1 location in the array

In other words, I need the number 1 to be in 1st position, 2 in 5th, 3 in 4th, 2 in 5th, and 3 in 6th.

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

For example, the output of this one would be: [1, 4, 5, 3, 2].

Is there a built in function for this or a simple code that can accomplish this goal?

What I’ve done so far:

import numpy as np
import random
array = np.arange(1,6)
print(array)
random.shuffle(array)
print(array)

>Solution :

Assuming you have all values in the range(1, len(a)), use numpy indexing:

a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 5, 4, 2, 3])
# or for a shuffled array
# b = a.copy() ; np.random.shuffle(b)

out = np.zeros_like(a)
out[b-1] = a

Output: array([1, 4, 5, 3, 2])

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