随机播放2D数组的行组 - NumPy

时间:2017-01-30 11:43:59

标签: numpy multidimensional-array shuffle

假设我有一个(50,5)数组。有没有办法让我根据数据点的行/序列分组进行混洗,即不是每行洗牌,而是洗牌,比如5行?

由于

1 个答案:

答案 0 :(得分:3)

方法#1:这是一种根据组大小重塑为3D数组的方法,索引到具有从{{获得的混洗索引的块的索引1}}并最终重塑为np.random.permutation -

2D

示例运行 -

N = 5 # Blocks of N rows
M,n = a.shape[0]//N, a.shape[1]
out = a.reshape(M,-1,n)[np.random.permutation(M)].reshape(-1,n)

方法#2:也可以简单地使用np.random.shuffle进行原位更改 -

In [141]: a
Out[141]: 
array([[89, 26, 12],
       [97, 60, 96],
       [94, 38, 54],
       [41, 63, 29],
       [88, 62, 48],
       [95, 66, 32],
       [28, 58, 80],
       [26, 35, 89],
       [72, 91, 38],
       [26, 70, 93]])

In [142]: N = 2 # Blocks of N rows

In [143]: M,n = a.shape[0]//N, a.shape[1]

In [144]: a.reshape(M,-1,n)[np.random.permutation(M)].reshape(-1,n)
Out[144]: 
array([[94, 38, 54],
       [41, 63, 29],
       [28, 58, 80],
       [26, 35, 89],
       [89, 26, 12],
       [97, 60, 96],
       [72, 91, 38],
       [26, 70, 93],
       [88, 62, 48],
       [95, 66, 32]])

示例运行 -

np.random.shuffle(a.reshape(M,-1,n))