numpy按行随机随机播放

编程入门 行业动态 更新时间:2024-10-28 12:29:03
本文介绍了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按行随机随机播放

本文发布于:2023-10-28 08:11:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!