在numpy数组的每一行中随机随机播放项目 [英] Randomly shuffle items in each row of numpy array

查看:67
本文介绍了在numpy数组的每一行中随机随机播放项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的numpy数组:

I have a numpy array like the following:

Xtrain = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [1, 7, 3]])

我想分别对每一行的项目进行洗牌,但是不希望对每一行进行相同的洗牌(在几个示例中只是对列的顺序进行洗牌).

I want to shuffle the items of each row separately, but do not want the shuffle to be the same for each row (as in several examples just shuffle column order).

例如,我想要类似以下的输出:

For example, I want an output like the following:

output = np.array([[3, 2, 1],
                   [4, 6, 5],
                   [7, 3, 1]])

如何以有效的方式随机地随机排列每一行?我实际的np数组超过100000行和1000列.

How can I randomly shuffle each of the rows randomly in an efficient way? My actual np array is over 100000 rows and 1000 columns.

推荐答案

由于只想改组列,因此只需执行

Since you want to only shuffle the columns you can just perform the shuffling on transposed of your matrix:

In [86]: np.random.shuffle(Xtrain.T)

In [87]: Xtrain
Out[87]: 
array([[2, 3, 1],
       [5, 6, 4],
       [7, 3, 1]])

请注意,

Note that random.suffle() on a 2D array shuffles the rows not items in each rows. i.e. changes the position of the rows. Therefor if your change the position of the transposed matrix rows you're actually shuffling the columns of your original array.

如果您仍然想要完全独立的改组,则可以为每行创建随机索引,然后使用简单的索引创建最终数组:

If you still want a completely independent shuffle you can create random indexes for each row and then create the final array with a simple indexing:

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]])

这篇关于在numpy数组的每一行中随机随机播放项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆