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