How to shuffle NumPy Array in Python?

Many times we want to shuffle an array for several reasons. For example, in Machine Learning, we need to shuffle the array to avoid bias because of fixed data ordering. Therefore in this tutorial, we will learn how to shuffle a NumPy array in Python.

We will initially, shuffle a 1-Dimensional array. Then we will try to shuffle a 2D  array. Later, we will shuffle only the columns of the 2D  array.

Shuffle a 1-Dimensional NumPy Array

To shuffle a 1D array, we will initially import the NumPy package.  Then we use the arange() function in Python which will return an array consisting of numbers starting from 1 to 10.  To shuffle this generated array, we use the shuffle() method of the random package in NumPy. This will return the shuffled array which we have printed.

import numpy as np

array = np.arange(10)

np.random.shuffle(array)
  
print(array)

Output:

[7 8 5 2 9 0 4 3 6 1]

Shuffle a 2-Dimensional NumPy Array

To shuffle a 2-dimensional array we follow similar steps as above. We use the random.randint() function to create a 2-Dimensional 3X3  array. This array will contain numbers starting from 1 to 50. Later, we use the shuffle() method to shuffle the elements of the array.

import numpy as np
array = np.random.randint(1,50, size=(3,3))
print(f"array:\n{array}\n")

np.random.shuffle(array)

print(f"shuffled array:\n{array}")

Output:

array:
[[37 38 34]
[14 3 27]
[27 15 42]]

shuffled array:
[[37 38 34]
[14 3 27]
[27 15 42]]

Shuffle the columns of a 2-Dimensional NumPy Array

The above-mentioned method shuffles the array in place. If you want to shuffle only the columns of the array then we can use the transpose of the array.

Since the shuffle() method takes no extra parameter to shuffle the array on any specific axis, so we swap the columns of this array with the rows. This will easily help in shuffling the columns of the array since the shuffle() method performs shuffling in place.

import numpy as np
array = np.random.randint(1,50, size=(3,3))
print(f"array:\n{array}\n")

np.random.shuffle(array.T)

print(f"shuffled array by columns:\n{array}")

Output:

array:
[[ 3 6 5]
[20 17 21]
[24 27 22]]

shuffled array by columns:
[[ 5 6 3]
[21 17 20]
[22 27 24]]

Thus we have reached the end of this tutorial on how to shuffle the NumPy array. To learn more about NumPy arrays click on the following link: Access a NumPy array by column in Python

Leave a Reply

Your email address will not be published. Required fields are marked *