Max*_*amy 14 python arrays numpy
假设我有一系列r维度(n, m).我想改组那个数组的列.
如果我使用numpy.random.shuffle(r)它洗牌线.我怎么才能洗牌?因此,第一列成为第二列,第三列成为第一列,等等.
例:
输入:
array([[ 1, 20, 100],
[ 2, 31, 401],
[ 8, 11, 108]])
Run Code Online (Sandbox Code Playgroud)
输出:
array([[ 20, 1, 100],
[ 31, 2, 401],
[ 11, 8, 108]])
Run Code Online (Sandbox Code Playgroud)
Max*_*amy 17
在问我想的时候我可能会改变转置的数组:
np.random.shuffle(np.transpose(r))
Run Code Online (Sandbox Code Playgroud)
它看起来像是完成了这项工作.我很感激评论,知道这是否是实现这一目标的好方法.
对于一般轴,您可以遵循以下模式:
>>> import numpy as np
>>>
>>> a = np.array([[ 1, 20, 100, 4],
... [ 2, 31, 401, 5],
... [ 8, 11, 108, 6]])
>>>
>>> print a[:, np.random.permutation(a.shape[1])]
[[ 4 1 20 100]
[ 5 2 31 401]
[ 6 8 11 108]]
>>>
>>> print a[np.random.permutation(a.shape[0]), :]
[[ 1 20 100 4]
[ 2 31 401 5]
[ 8 11 108 6]]
>>>
Run Code Online (Sandbox Code Playgroud)
因此,比您的答案更进一步:
编辑:我很容易弄错这是如何工作的,所以我在每一步插入我对矩阵状态的理解。
r == 1 2 3
4 5 6
6 7 8
r = np.transpose(r)
r == 1 4 6
2 5 7
3 6 8 # Columns are now rows
np.random.shuffle(r)
r == 2 5 7
3 6 8
1 4 6 # Columns-as-rows are shuffled
r = np.transpose(r)
r == 2 3 1
5 6 4
7 8 6 # Columns are columns again, shuffled.
Run Code Online (Sandbox Code Playgroud)
然后将恢复到正确的形状,重新排列列。
矩阵的转置 == 该矩阵的转置,或者,[A^T]^T == A。因此,您需要在洗牌后进行第二次转置(因为转置不是洗牌)以使其再次处于适当的形状。
编辑:OP 的答案跳过存储换位,而是让 shuffle 像 r 一样对 r 进行操作。