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

Why does np.random.shuffle() shuffle current and previous versions of an array?

I came across a problem recently using np.random.shuffle() where I have an array of training indices. In an effort to create a new array with shuffled indices (and keep my original indices as is) I used np.random.shuffle(). I came to find out, after an embarrassing amount of time that while np.random.shuffle() created a new array of shuffled indices, it also shuffled my original array, despite this array not being in the function.

Here is a simple example to demonstrate my original problem. Does anyone know why this happens?

np.random.seed(124)
array1 = [1,2,3,4,5]
print(f' array 1 is {array1}')
array2 = array1
np.random.shuffle(array2) 
print(f' array 2 is {array2}')
print(f' array 1 is {array1}')

Output:
array 1 is [1, 2, 3, 4, 5]
array 2 is [1, 4, 3, 2, 5]
array 1 is [1, 4, 3, 2, 5]

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

>Solution :

When you set array2 = array1 you link one object to the other, instead of only copying its content. Now, array2 is simply another name for the original object array1. Therefore, the shuffling of array2 is also contained in array1. If you simply want to copy the content of array1 into a new separate and independent object you can use:
array2 = array1.copy().

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