Shuffle an array with python, randomize array item

2019-01-06 11:14发布

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

10条回答
家丑人穷心不美
2楼-- · 2019-01-06 11:42
# 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]
查看更多
Anthone
3楼-- · 2019-01-06 11:50
sorted(array, key = lambda x: random.random())
查看更多
孤傲高冷的网名
4楼-- · 2019-01-06 11:51

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
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-06 11:54

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.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-06 11:54

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.

查看更多
走好不送
7楼-- · 2019-01-06 11:57
import random
random.shuffle(array)
查看更多
登录 后发表回答