How to shuffle an array in Numpy?

Learn how to shuffle NumPy arrays using np.random.shuffle() for randomizing element order in-place.

Numpy random shuffle array

Shuffling an array

With Numpy you can easily shuffle an array. Just use Numpy random shuffle method. This will shuffle your array.

import numpy as np

my_list = [1, 2, 5, 7, 9, 13]
print(f"My list is: \n{my_list}")

my_array = np.array(my_list)

np.random.shuffle(my_array)
print(f"My random shuffle array is: \n{my_array}")

Numpy random shuffle array

As you can see the order of values has been changed.

See also  How to stack arrays in Numpy?

Other parameters of Numpy random shuffle function

The random.shuffle method in Numpy has several other parameters that can be used to customize the output.

  • axis: The axis along which the array will be shuffled. The default value is None, which means that the array will be shuffled in place.
    • If axis=0, the elements in the first dimension will be shuffled.
    • If axis=1, the elements in the second dimension will be shuffled.
    • And so on.
  • random_state: shuffle() does NOT have random_state parameter; use np.random.seed() for reproducibility or RandomState object.
See also  How to solve ValueError: setting an array element with a sequence

For example, the following code will shuffle the array along the first axis:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])

np.random.seed(42)
np.random.shuffle(my_array)
print("Shuffled:", my_array)

np.random.seed(42)
my_array2 = np.array([1, 2, 3, 4, 5])
np.random.shuffle(my_array2)
print("Same shuffle:", my_array2)
print(f"Arrays equal: {np.array_equal(my_array, my_array2)}")