给定以下 NumPy 数组,
> a = array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
洗牌很简单,
> shuffle(a[0])
> a
array([[4, 2, 1, 3, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
是否可以使用索引符号独立地随机排列每一行?或者你是否必须遍历数组。我想到了类似的东西,
> numpy.shuffle(a[:])
> a
array([[4, 2, 3, 5, 1],[3, 1, 4, 5, 2],[4, 2, 1, 3, 5]]) # Not the real output
虽然这显然行不通。
最佳答案
使用 rand+argsort
技巧的矢量化解决方案
我们可以生成沿指定轴的唯一索引,并使用 advanced-indexing
对输入数组进行索引。要生成唯一索引,我们将使用 random float generation + sort
trick ,从而给我们一个向量化的解决方案。我们还将其概括为涵盖通用 n-dim
数组以及带有 np.take_along_axis
的通用 axes
.最终的实现看起来像这样 -
def shuffle_along_axis(a, axis):
idx = np.random.rand(*a.shape).argsort(axis=axis)
return np.take_along_axis(a,idx,axis=axis)
请注意,此随机播放不会就地进行并返回随机播放的副本。
sample 运行-
In [33]: a
Out[33]:
array([[18, 95, 45, 33],
[40, 78, 31, 52],
[75, 49, 42, 94]])
In [34]: shuffle_along_axis(a, axis=0)
Out[34]:
array([[75, 78, 42, 94],
[40, 49, 45, 52],
[18, 95, 31, 33]])
In [35]: shuffle_along_axis(a, axis=1)
Out[35]:
array([[45, 18, 33, 95],
[31, 78, 52, 40],
[42, 75, 94, 49]])
关于python - 沿给定轴打乱 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5040797/