python:为什么random.shuffle会更改数组

时间:2021-04-05 21:22:47

I'm using random.shuffle to shuffle a 2D numpy array. I met with the following problem:

我正在使用random.shuffle来改组2D numpy数组。我遇到了以下问题:

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 1D array, everything is correct. But while shuffling 2D array, the result becomes strange.

结果表明,当洗牌1D阵列时,一切都是正确的。但是在改组2D阵列时,结果变得奇怪。

Why is the third row of the original array thrown away and the first row duplicated by twice?

为什么抛弃原始数组的第三行并将第一行重复两次?

I know there could be solutions to solve this problem, such as firstly shuffle a 1D array indicating the row ids and then extract the 2D array in the order of the shuffled ids. But I do want to make clear what happens to the implementation of random.shuffle, or what's wrong with my code.

我知道可以有解决方案来解决这个问题,例如首先洗牌指示行ID的1D数组,然后按照混洗ID的顺序提取2D数组。但我确实想弄清楚random.shuffle的实现会发生什么,或者我的代码出了什么问题。

1 个解决方案

#1


8  

Shuffle from the random module isn’t made to deal with numpy arrays since it’s not exactly the same as nested python lists. You should use the numpy.random module’s shuffle instead.

来自随机模块的随机播放不是为了处理numpy数组,因为它与嵌套的python列表不完全相同。您应该使用numpy.random模块的shuffle。

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

#1


8  

Shuffle from the random module isn’t made to deal with numpy arrays since it’s not exactly the same as nested python lists. You should use the numpy.random module’s shuffle instead.

来自随机模块的随机播放不是为了处理numpy数组,因为它与嵌套的python列表不完全相同。您应该使用numpy.random模块的shuffle。

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