[英]Numpy shuffle 3-D numpy array by row
Suppose I have the following 3D matrix: 假设我有以下3D矩阵:
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
and behind it (3rd dimension): 它背后(第三维):
aaa AAA
bbb BBB
ccc CCC
Defined as the following if I am correct: 如果我是正确的,则定义如下:
import numpy as np
x = np.array([[[1,1,1],
[2,2,2],
[3,3,3]],
[["a","a","a"],
["b","b","b"],
["c","c","c"]]])
And I want to randomly shuffle my 3D-array by row becoming something like this: 而且我希望随机地将我的3D阵列随机改组成这样的东西:
2 2 2 2 2 2
1 1 1 1 1 1
3 3 3 3 3 3
behind: 背后:
bbb BBB
aaa AAA
ccc CCC
*Note that a always belongs to 1, b to 2 and c to 3 (same rows) *请注意,a始终属于1,b为2,c为3(相同行)
How do I achieve this? 我该如何实现这一目标?
Using np.random.shuffle
: 使用
np.random.shuffle
:
import numpy as np
x = np.array([[[1,1,1],
[2,2,2],
[3,3,3]],
[["a","a","a"],
["b","b","b"],
["c","c","c"]]])
ind = np.arange(x.shape[1])
np.random.shuffle(ind)
x[:, ind, :]
Output: 输出:
array([[['1', '1', '1'],
['3', '3', '3'],
['2', '2', '2']],
[['a', 'a', 'a'],
['c', 'c', 'c'],
['b', 'b', 'b']]], dtype='<U21')
Simply use np.random.shuffle
after bringing up the second axis as the first one, as the shuffle
function works along the first axis and does the shuffling in-place - 在将第二个轴作为第一个轴后,简单地使用
np.random.shuffle
,因为shuffle
函数沿着第一个轴工作并且就地进行洗牌 -
np.random.shuffle(x.swapaxes(0,1))
Sample run - 样品运行 -
In [203]: x
Out[203]:
array([[['1', '1', '1'],
['2', '2', '2'],
['3', '3', '3']],
[['a', 'a', 'a'],
['b', 'b', 'b'],
['c', 'c', 'c']]], dtype='<U21')
In [204]: np.random.shuffle(x.swapaxes(0,1))
In [205]: x
Out[205]:
array([[['3', '3', '3'],
['2', '2', '2'],
['1', '1', '1']],
[['c', 'c', 'c'],
['b', 'b', 'b'],
['a', 'a', 'a']]], dtype='<U21')
This should be pretty efficient as we found out in this Q&A
. 我们在
this Q&A
发现,这应该非常有效。
Alternatively, two other ways to permute axes would be - 或者,另外两种置换轴的方法是 -
np.moveaxis(x,0,1)
x.transpose(1,0,2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.