How to shuffle an array python

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

Machavity

30.1k26 gold badges87 silver badges98 bronze badges

asked Jan 23, 2009 at 18:34

3

import random
random.shuffle[array]

answered Jan 23, 2009 at 18:37

David ZDavid Z

124k26 gold badges249 silver badges275 bronze badges

9

import random
random.shuffle[array]

answered Jan 23, 2009 at 18:38

Douglas LeederDouglas Leeder

51.1k9 gold badges91 silver badges136 bronze badges

3

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.

answered Jul 24, 2017 at 3:30

Qy ZuoQy Zuo

2,40422 silver badges21 bronze badges

4

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']]:

answered Dec 20, 2011 at 22:05

Mark RhodesMark Rhodes

9,7834 gold badges46 silver badges51 bronze badges

5

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

import random
new_array = random.sample[ array, len[array] ]

answered Mar 29, 2017 at 18:37

Charlie ParkerCharlie Parker

11.4k41 gold badges160 silver badges267 bronze badges

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.

dbliss

9,66815 gold badges49 silver badges81 bronze badges

answered Oct 28, 2013 at 9:23

Shuai ZhangShuai Zhang

1,9413 gold badges21 silver badges23 bronze badges

2

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

this is O[log[N]] btw

answered Sep 21, 2018 at 18:37

JamesJames

13k5 gold badges57 silver badges81 bronze badges

4

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.

answered Nov 18, 2016 at 9:55

SaberSaber

1942 silver badges8 bronze badges

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

answered Jan 17, 2017 at 11:09

JeevaJeeva

1,6872 gold badges14 silver badges19 bronze badges

1

# 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]

MBT

18.9k17 gold badges77 silver badges99 bronze badges

answered Nov 14, 2018 at 15:41

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 2x3 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[].

answered Feb 21, 2020 at 14:01

Wise CloudWise Cloud

4014 silver badges5 bronze badges

How do you shuffle an array value in Python?

Shuffle an Array in Python Using the random. The random. shuffle[] method takes a sequence as input and shuffles it. The important thing to note here is that the random. shuffle[] does not return a new sequence as output but instead shuffles the original sequence.

How can I shuffle an array?

Write the function shuffle[array] that shuffles [randomly reorders] elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle[arr]; // arr = [3, 2, 1] shuffle[arr]; // arr = [2, 1, 3] shuffle[arr]; // arr = [3, 1, 2] // ...

How do you shuffle in Python?

To shuffle strings or tuples, use random. sample[] , which creates a new object. random. sample[] returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

How do you shuffle two arrays in Python?

Use the syntax array[p] with p as the previous result to shuffle array based on p ..
array1 = np. array[[[1, 1], [2, 2], [3, 3]]].
array2 = np. array[[1, 2, 3]].
shuffler = np. random. permutation[len[array1]].

Chủ Đề