本文介绍了沿给定轴打乱 NumPy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 NumPy 数组,

Given the following NumPy array,

> a = array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])

很简单,可以随机排列一行,

it's simple enough to shuffle a single row,

> shuffle(a[0])
> a
array([[4, 2, 1, 3, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])

是否可以使用索引符号来独立地对每一行进行洗牌?或者你必须遍历数组.我想到了类似的东西,

Is it possible to use indexing notation to shuffle each of the rows independently? Or do you have to iterate over the array. I had in mind something like,

> numpy.shuffle(a[:])
> a
array([[4, 2, 3, 5, 1],[3, 1, 4, 5, 2],[4, 2, 1, 3, 5]]) # Not the real output

虽然这显然行不通.

推荐答案

你必须多次调用 numpy.random.shuffle() 因为你是在独立地洗牌多个序列.numpy.random.shuffle() 适用于任何可变序列,实际上不是 ufunc.分别对二维数组 a 的所有行进行 shuffle 的最短和最有效的代码可能是

You have to call numpy.random.shuffle() several times because you are shuffling several sequences independently. numpy.random.shuffle() works on any mutable sequence and is not actually a ufunc. The shortest and most efficient code to shuffle all rows of a two-dimensional array a separately probably is

list(map(numpy.random.shuffle, a))

有些人更喜欢将其写为列表推导式:

Some people prefer to write this as a list comprehension instead:

[numpy.random.shuffle(x) for x in a]

这篇关于沿给定轴打乱 NumPy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:15