The NumPy shuffle() function allows you to alter an array by shuffling its elements randomly.
The function performs the shuffling in-place, which modifies the original array.
Let us discuss.
Function Syntax
The function provides a straightforward syntax with minimal parameters. The syntax is expressed below:
1 | random.shuffle(x) |
Parameters
The function accepts only the array, list, or sequence to be shuffled as the parameter.
Return
As the function performs an in-place action, it returns a None. However, it is safe to say that the function returns a shuffled version of the input array.
Example #1
Let us take an example as shown below:
1 2 3 4 5 | # import numpy import numpy as np arr = np.array([1,2,3,4,5,6,7,8]) np.random.shuffle(arr) print(arr) |
The code above takes the input array and shuffles the elements in any random order.
An example resulting array is as shown:
1 | [2 8 4 6 5 3 7 1] |
Example #2
The shuffle() function will shuffle multi-dimensional arrays along the first axis. An example is as illustrated below:
1 2 3 | arr = np.array([[1,2,3], [4,5,6], [7,8,9]]) np.random.shuffle(arr) print(arr) |
The code above should return an example shuffled array as shown:
1 2 3 | [[7 8 9] [4 5 6] [1 2 3]] |
Terminating
In this article, we discussed how to use the NumPy shuffle() function to shuffle elements of an array in any random order.
Thanks for reading!!