How to shuffle an array in Numpy?

Let’s see how to shuffle an array in Numpy Python library.
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 Flatten an Array 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: A random number generator object. If not specified, a new random number generator will be created.
See also  Troubleshooting IndexError in NumPy Advanced Indexing Scenarios

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

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, axis=0)
print(f"My random shuffle array is: \n{my_array}")