使用python随机整理数组,使用python随机化数组项顺序

问题:使用python随机整理数组,使用python随机化数组项顺序

用python重组数组的最简单方法是什么?

What’s the easiest way to shuffle an array with python?


回答 0

import random
random.shuffle(array)
import random
random.shuffle(array)

回答 1

import random
random.shuffle(array)
import random
random.shuffle(array)

回答 2

使用sklearn的另一种方法

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

输出:

[2, 1, 3]
['two', 'one', 'three']

优点:您可以同时随机分配多个阵列,而不会破坏映射。并且“ random_state”可以控制改组以实现可重现的行为。

Alternative way to do this using sklearn

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

Output:

[2, 1, 3]
['two', 'one', 'three']

Advantage: You can random multiple arrays simultaneously without disrupting the mapping. And ‘random_state’ can control the shuffling for reproducible behavior.


回答 3

其他答案最简单,但是令人讨厌的是该random.shuffle方法实际上不返回任何内容,它只是对给定列表进行排序。如果要链接调用,或者只想在一行中声明一个改组数组,则可以执行以下操作:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

然后,您可以执行以下操作:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

The other answers are the easiest, however it’s a bit annoying that the random.shuffle method doesn’t actually return anything – it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

Then you can do lines like:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

回答 4

当处理常规的Python列表时,random.shuffle()将按照前面的答案所示进行操作。

但是,当谈到ndarraynumpy.array)时,random.shuffle似乎打破了原来的ndarray。这是一个例子:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

只需使用: np.random.shuffle(a)

像一样random.shufflenp.random.shuffle就地调整数组的位置。

When dealing with regular Python lists, random.shuffle() will do the job just as the previous answers show.

But when it come to ndarray(numpy.array), random.shuffle seems to break the original ndarray. Here is an example:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

Just use: np.random.shuffle(a)

Like random.shuffle, np.random.shuffle shuffles the array in-place.


回答 5

万一您想要一个新的数组,可以使用sample

import random
new_array = random.sample( array, len(array) )

Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )

回答 6

您可以使用随机键对数组进行排序

sorted(array, key = lambda x: random.random())

密钥只能读取一次,因此排序期间的比较项目仍然有效。

但是看起来好像random.shuffle(array)会更快,因为它是用C编写的

You can sort your array with random key

sorted(array, key = lambda x: random.random())

key only be read once so comparing item during sort still efficient.

but look like random.shuffle(array) will be faster since it written in C


回答 7

除了前面的答复,我还要介绍另一个功能。

numpy.random.shuffle以及random.shuffle执行就地改组。但是,如果要返回经过改组的数组,numpy.random.permutation则可以使用该函数。

In addition to the previous replies, I would like to introduce another function.

numpy.random.shuffle as well as random.shuffle perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation is the function to use.


回答 8

我不知道我曾经用过,random.shuffle()但是它返回“ None”给我,所以我写了这个,可能对某人有帮助

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

I don’t know I used random.shuffle() but it return ‘None’ to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

回答 9

# arr = numpy array to shuffle

def shuffle(arr):
    a = numpy.arange(len(arr))
    b = numpy.empty(1)
    for i in range(len(arr)):
        sel = numpy.random.random_integers(0, high=len(a)-1, size=1)
        b = numpy.append(b, a[sel])
        a = numpy.delete(a, sel)
    b = b[1:].astype(int)
    return arr[b]
# arr = numpy array to shuffle

def shuffle(arr):
    a = numpy.arange(len(arr))
    b = numpy.empty(1)
    for i in range(len(arr)):
        sel = numpy.random.random_integers(0, high=len(a)-1, size=1)
        b = numpy.append(b, a[sel])
        a = numpy.delete(a, sel)
    b = b[1:].astype(int)
    return arr[b]

回答 10

请注意,random.shuffle()不应在多维数组上使用它,因为它会引起重复。

假设您想沿数组的第一维进行混洗,我们可以创建以下测试示例,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

因此,沿着第一个轴,第i个元素对应于2×3矩阵,其中所有元素都等于i。

如果我们对多维数组使用正确的随机播放功能,即np.random.shuffle(x)该数组将根据需要沿第一个轴随机播放。但是,使用random.shuffle(x)会导致重复。您可以通过len(np.unique(x))在改组后运行来检查此问题,使用时可以得到10(按预期),np.random.shuffle()但使用时只有5 random.shuffle()

Be aware that random.shuffle() should not be used on multi-dimensional arrays as it causes repetitions.

Imagine you want to shuffle an array along its first dimension, we can create the following test example,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

so that along the first axis, the i-th element corresponds to a 2×3 matrix where all the elements are equal to i.

If we use the correct shuffle function for multi-dimensional arrays, i.e. np.random.shuffle(x), the array will be shuffled along the first axis as desired. However, using random.shuffle(x) will cause repetitions. You can check this by running len(np.unique(x)) after shuffling which gives you 10 (as expected) with np.random.shuffle() but only around 5 when using random.shuffle().