Shuffle a numpy array Shuffle a numpy array numpy numpy

Shuffle a numpy array


You can tell np.random.shuffle to act on the flattened version:

>>> a = np.arange(9).reshape((3,3))>>> aarray([[0, 1, 2],       [3, 4, 5],       [6, 7, 8]])>>> np.random.shuffle(a.flat)>>> aarray([[3, 5, 8],       [7, 6, 2],       [1, 4, 0]])


You could shuffle a.flat:

>>> np.random.shuffle(a.flat)>>> aarray([[6, 1, 2],       [3, 5, 0],       [7, 8, 4]])


I think this is very important to note.
You can use random.shuffle(a) if a is 1-D numpy array.If it is N-D (where N > 2) than

random.shuffle(a)

will spoil your data and return some random thing.As you can see here:

import randomimport numpy as npa=np.arange(9).reshape((3,3))random.shuffle(a)print a[[0 1 2] [3 4 5] [3 4 5]]

This is a known bug (or feature?) of numpy.

So, use only numpy.random.shuffle(a) for numpy arrays.