numpy按行随机随机播放 [英] numpy random shuffle by row independently

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

问题描述

我有以下数组:

 a= array([[  1,  2, 3],
           [  1,  2, 3],
           [  1,  2, 3])

我知道np.random,shuffle(a.T)会沿着行对数组进行随机排列,但是我需要的是独立地对每一行进行换行.如何在numpy中完成?速度至关重要,因为将有几百万行.

I understand that np.random,shuffle(a.T) will shuffle the array along the row, but what I need is it to shuffe each row idependently. How can this be done in numpy? Speed is critical as there will be several million rows.

对于此特定问题,每行将包含相同的起始填充.

For this specific problem, each row will contain the same starting population.

推荐答案

import numpy as np
np.random.seed(2018)

def scramble(a, axis=-1):
    """
    Return an array with the values of `a` independently shuffled along the
    given axis
    """ 
    b = a.swapaxes(axis, -1)
    n = a.shape[axis]
    idx = np.random.choice(n, n, replace=False)
    b = b[..., idx]
    return b.swapaxes(axis, -1)

a = a = np.arange(4*9).reshape(4, 9)
# array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8],
#        [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
#        [18, 19, 20, 21, 22, 23, 24, 25, 26],
#        [27, 28, 29, 30, 31, 32, 33, 34, 35]])

print(scramble(a, axis=1))

收益

[[ 3  8  7  0  4  5  1  2  6]
 [12 17 16  9 13 14 10 11 15]
 [21 26 25 18 22 23 19 20 24]
 [30 35 34 27 31 32 28 29 33]]

同时沿0轴加扰:

print(scramble(a, axis=0))

收益

[[18 19 20 21 22 23 24 25 26]
 [ 0  1  2  3  4  5  6  7  8]
 [27 28 29 30 31 32 33 34 35]
 [ 9 10 11 12 13 14 15 16 17]]


这是通过首先将目标轴与最后一个轴交换来实现的:


This works by first swapping the target axis with the last axis:

b = a.swapaxes(axis, -1)

这是用于标准化处理一个轴的代码的常见技巧. 它将一般情况简化为处理最后一个轴的特定情况. 由于在NumPy 1.10或更高版本中,swapaxes返回一个视图,因此不涉及复制,因此调用swapaxes的速度非常快.

This is a common trick used to standardize code which deals with one axis. It reduces the general case to the specific case of dealing with the last axis. Since in NumPy version 1.10 or higher swapaxes returns a view, there is no copying involved and so calling swapaxes is very quick.

现在,我们可以为最后一个轴生成新的索引顺序:

Now we can generate a new index order for the last axis:

n = a.shape[axis]
idx = np.random.choice(n, n, replace=False)

现在,我们可以(分别沿最后一个轴)随机播放b:

Now we can shuffle b (independently along the last axis):

b = b[..., idx]

,然后反转swapaxes以返回形状为a的结果:

and then reverse the swapaxes to return an a-shaped result:

return b.swapaxes(axis, -1)

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

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