Python: why random.shuffle modifies an array

I am using random.shuffle to mix a 2D numpy array. I encountered the following problem:

 import numpy as np from random import shuffle as sf b = np.array([1,2,3,4,5]) print b # [1 2 3 4 5] sf(b) print b # [1 4 5 3 2] a = np.array([[1,2,3],[4,5,6],[7,8,9]]) print a # [[1 2 3] # [4 5 6] # [7 8 9]] sf(a) print a # [[1 2 3] # [4 5 6] # [1 2 3]] 

The result shows that when shuffling the 1D array, everything is correct. But when you move the 2D array, the result becomes strange.

Why is the third row of the original array selected and the first row duplicated twice?

I know there may be solutions to solve this problem, for example, first shuffle the 1D array indicating the row identifiers, and then extract the 2D array in the order of the shuffled identifiers. But I want to clearly indicate what happens to the implementation of random.shuffle , or what is wrong with my code.

+5
source share
1 answer

Shuffling from the random module is not designed to work with numpy arrays, since it does not quite match python nested lists. You should use numpy.random shuffle modules instead.

 import numpy as np from numpy.random import shuffle arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) shuffle(arr) print(arr) # output: # [[4 5 6] # [1 2 3] # [7 8 9]] 
+8
source

Source: https://habr.com/ru/post/1269504/


All Articles