我有一个numpy数组,如下所示:
Xtrain = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [1, 7, 3]])我想对每一行的项目分别进行混洗,但不希望每一行的混洗都是相同的(就像在几个示例中一样,只是混洗列的顺序)。
例如,我需要如下所示的输出:
output = np.array([[3, 2, 1],
                   [4, 6, 5],
                   [7, 3, 1]])如何以有效的方式随机地对每一行进行随机洗牌?我实际的np数组有超过100000行和1000列。
发布于 2018-05-28 01:08:37
因为您只想对列进行混洗,所以可以只对转置后的矩阵执行:
In [86]: np.random.shuffle(Xtrain.T)
In [87]: Xtrain
Out[87]: 
array([[2, 3, 1],
       [5, 6, 4],
       [7, 3, 1]])请注意,2D数组上的random.suffle()会对行进行混洗,而不是对每行中的项进行混洗。即改变行的位置。因此,如果你改变了转置矩阵行的位置,你实际上就是在打乱原始数组的列。
如果你仍然想要一个完全独立的混洗,你可以为每一行创建随机索引,然后用一个简单的索引创建最终的数组:
In [172]: def crazyshuffle(arr):
     ...:     x, y = arr.shape
     ...:     rows = np.indices((x,y))[0]
     ...:     cols = [np.random.permutation(y) for _ in range(x)]
     ...:     return arr[rows, cols]
     ...: 演示:
In [173]: crazyshuffle(Xtrain)
Out[173]: 
array([[1, 3, 2],
       [6, 5, 4],
       [7, 3, 1]])
In [174]: crazyshuffle(Xtrain)
Out[174]: 
array([[2, 3, 1],
       [4, 6, 5],
       [1, 3, 7]])发布于 2018-05-28 00:55:45
来自:https://github.com/numpy/numpy/issues/5173
def disarrange(a, axis=-1):
    """
    Shuffle `a` in-place along the given axis.
    Apply numpy.random.shuffle to the given axis of `a`.
    Each one-dimensional slice is shuffled independently.
    """
    b = a.swapaxes(axis, -1)
    # Shuffle `b` in-place along the last axis.  `b` is a view of `a`,
    # so `a` is shuffled in place, too.
    shp = b.shape[:-1]
    for ndx in np.ndindex(shp):
        np.random.shuffle(b[ndx])
    return发布于 2018-05-28 01:51:19
这个解决方案无论如何都不是很有效,但我觉得很有趣,所以把它写了下来。基本上,您将整理数组,并创建一个行标签数组和一个索引数组。您可以混洗索引数组,并用它索引原始和行标签数组。然后,将稳定的 argsort应用于行标签,将数据收集到行中。应用该索引、整形和viola,按行独立地混洗数据:
import numpy as np
r, c = 3, 4  # x.shape
x = np.arange(12) + 1  # Already raveled 
inds = np.arange(x.size)
rows = np.repeat(np.arange(r).reshape(-1, 1), c, axis=1).ravel()
np.random.shuffle(inds)
x = x[inds]
rows = rows[inds]
inds = np.argsort(rows, kind='mergesort')
x = x[inds].reshape(r, c)这是一个IDEOne Link
https://stackoverflow.com/questions/50554272
复制相似问题