Reputation: 1686
I was trying to shuffle 2D array, and I encountered some stange behavior, that can be resumed with the following code:
import random
import numpy
a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
random.shuffle(a)
print 'With rand\n', a
a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
numpy.random.shuffle(a)
print 'With numpy\n', a
Output
With rand
[[1 2 3]
[1 2 3]
[1 2 3]]
With numpy
[[4 5 6]
[7 8 9]
[1 2 3]]
As you can see, with random
library (my first try), it seems to overwrite elements (or something else, I really don't understand what happen here), consequently the shuffling is not performed.
However with numpy
library, it works perfectly.
Can anyone explain me why? I.e. where does this difference come from? And if possible, what does the random.shuffle
function does with 2D array?
Thanks,
Upvotes: 2
Views: 4117
Reputation: 967
In a check for random
source code..
https://svn.python.org/projects/stackless/trunk/Lib/random.py
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
if random is None:
random = self.random
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]
the last line as you see: make the shuffle
fails because numpy somehow perform the last line in parts
, but python lists perform it altogether ..
Upvotes: 2
Reputation: 1675
random.shuffle
is designed to work with a list
and not an array
. Basically, you should use random.shuffle
whenever you have a list
and np.random.shuffle
when you are working with an array
.
a = [[1,2,3],[4,5,6],[7,8,9]]
random.shuffle(a)
b = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
numpy.random.shuffle(b)
Upvotes: 0