mardi 9 mai 2017

Shuffle 2D array

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,




Aucun commentaire:

Enregistrer un commentaire