问题描述
给出以下NumPy数组,
Given the following NumPy array,
> a = array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
它很简单,可以随机排列一行,
it's simple enough to shuffle a single row,
> shuffle(a[0])
> a
array([[4, 2, 1, 3, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
是否可以使用索引符号独立地随机排列每一行?还是您必须遍历数组.我想到过类似的东西,
Is it possible to use indexing notation to shuffle each of the rows independently? Or do you have to iterate over the array. I had in mind something like,
> numpy.shuffle(a[:])
> a
array([[4, 2, 3, 5, 1],[3, 1, 4, 5, 2],[4, 2, 1, 3, 5]]) # Not the real output
尽管这显然行不通.
推荐答案
您必须多次调用numpy.random.shuffle()
,因为您要分别改组多个序列. numpy.random.shuffle()
适用于任何可变序列,实际上不是ufunc
.分别洗排二维数组a
的所有行的最短,最有效的代码可能是
You have to call numpy.random.shuffle()
several times because you are shuffling several sequences independently. numpy.random.shuffle()
works on any mutable sequence and is not actually a ufunc
. The shortest and most efficient code to shuffle all rows of a two-dimensional array a
separately probably is
map(numpy.random.shuffle, a)
这篇关于沿给定轴改组NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!