How to randomly shuffle an array in python using numpy

Published: May 24, 2018

DMCA.com Protection Status

1D array

To randomly shuffle a 1D array in python, there is the numpy function called: shuffle, illustration with the following array:

\begin{equation}
M =
\left( \begin{array}{cccccc}
4 & 8 & 15 & 16 & 23 & 42
\end{array}\right)
\end{equation}

>>> import numpy as np
>>> M = np.array([4,8,15,16,23,42])
>>> np.random.shuffle(M)
>>> M
array([15, 16,  8, 42, 23,  4])
>>> np.random.shuffle(M)
>>> M
array([ 8, 42, 23, 15, 16,  4])
>>>

2D (or more) array

Warning : In the case of a 2D array the function shuffle is going to permute randomly the array rows. Example:

\begin{equation}
M =
\left( \begin{array}{ccc}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{array}\right)
\end{equation}

>>> import numpy as np
>>> M = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> M
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.random.shuffle(M)
>>> M
array([[7, 8, 9],
       [1, 2, 3],
       [4, 5, 6]])
>>> np.random.shuffle(M)
>>> M
array([[4, 5, 6],
       [7, 8, 9],
       [1, 2, 3]])

To randomly shuffle a 2D(or more) array in python, it is necessary to transform the array to a 1d array (using ravel function), then using shuffle and reshape the array to its original shape:

>>> import numpy as np
>>> M = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> M
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> M = M.ravel()
>>> M
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.random.shuffle(M)
>>> M
array([3, 1, 9, 5, 2, 8, 4, 7, 6])
>>> M = M.reshape(3,3)
>>> M
array([[3, 1, 9],
       [5, 2, 8],
       [4, 7, 6]])

returns

\begin{equation}
M =
\left( \begin{array}{ccc}
3 & 1 & 9 \\
5 & 2 & 8 \\
4 & 7 & 6
\end{array}\right)
\end{equation}

References