What is random permutation of an array from NumPy in Python?
Overview
The Random module in NumPy helps make permutations of elements of an array.
Permutation refers to the arrangement of elements in an array. For example, [3, 1, 2] and [1, 3, 2] are permutations of the array elements in [1, 2, 3] and vice versa.
Methods of random permutation of elements
To make a permutation of elements in an array, we need to choose either of these two methods:
Shuffle()methodPermutation()method
The shuffle() method
The shuffle() method changes or “shuffles” the arrangements of elements in an array randomly. This method modifies the original array.
Syntax
random.shuffle(array)
Parameter value
The shuffle() method takes a single parameter value: an array object.
Code example
from numpy import random, arrayfrom random import shuffle# creating an arraymy_array = array([1, 2, 3, 4, 5])# calling the shuffle() methodshuffle(my_array)print(my_array)
Code explanation
- Line 1: We import the
randomandarraymodules fromnumpy. - Line 2: We import the
shufflemethod fromrandommodule. - Line 5: We create an array
my_arrayusing thearray()function. - Line 8: We call the
shuffle()method on the arraymy_array. - Line 10: We print the modified array
my_array.
The permutation() method
The permutation() method is the same as the shuffle() method, but it returns a re-arranged array and does not modify the original array.
Syntax
random.permutation(array)
Parameter value
The permutation() method takes a single parameter value: an array object.
Code example
from numpy import random, arrayfrom random import permutation# creating an arraymy_array = array([1, 2, 3, 4, 5])# calling the permutation() methodprint(permutation(my_array))print(my_array)
Code explanation
- Line 1: We import the
randomandarraymodules fromnumpy. - Line 4: We create an array
my_arrayusing thearray()function. - Line 7: We call the
permutation()method on the arraymy_arrayand print the re-arranged array. - Line 9: To show that the
permutation()function does not modify the original array, we print the arraymy_array.