Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle a numpy array

I have a 2-d numpy array that I would like to shuffle. Is the best way to reshape it to 1-d, shuffle and reshape again to 2-d or is it possible to shuffle without reshaping?

just using the random.shuffle doesn't yield expected results and numpy.random.shuffle shuffles only rows:

import random
import numpy as np
a=np.arange(9).reshape((3,3))
random.shuffle(a)
print a

[[0 1 2]
 [3 4 5]
 [3 4 5]]

a=np.arange(9).reshape((3,3))
np.random.shuffle(a)
print a

[[6 7 8]
 [3 4 5]
 [0 1 2]]
like image 421
Artturi Björk Avatar asked Mar 15 '14 16:03

Artturi Björk


1 Answers

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

>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.random.shuffle(a.flat)
>>> a
array([[3, 5, 8],
       [7, 6, 2],
       [1, 4, 0]])
like image 82
DSM Avatar answered Sep 30 '22 15:09

DSM